我正在调整一个函数,该函数打开一个制表的.txt文件并解析为2d数组。
我的大多数制表.txt文件都运行良好,但是我得到的Error runtime 9
是这个特定文件,是因为我的文件的时间或回车符或制表符等特殊格式吗?我该如何调试?
感谢您的帮助
我的代码:
'Option Explicit
Sub test()
'On Error Resume Next 'just in case... comment this in dev. mode to see debug message
Dim myArr() As Variant
Dim m As Integer
Dim Path As String, Delim As String
Dim ArchiFile As String
Delim = vbTab 'if Tabullated .txt 'vbTab Chr( 9 ) Tab character
'Delim = "," 'if Coma Separated Value .csv
ArchiFile = "C:\Users\diego\Desktop\RoofDataBase.txt"
'Error runtime 9
'Download file here https://www.dropbox.com/s/zg8otjfhtb5vxb2/RoofDataBase.txt?dl=0
Path = "C:\Users\diego\Desktop\A340.txt"
'Works!
'Download file here https://www.dropbox.com/s/6vosudkytx6vjjl/A340.txt?dl=0
'****** WHERE THE MAGIC HAPPEN *****
'myArr = TwoDArr(ArchiFile, Delim) 'not working with roof export? it does open and loop trough in function but not save in array
myArr = TwoDArr(Path, Delim) 'works for schema exports (perhaps suze?
'********* END OF MAGIC ************
Debug.Print "sub - "; myArr(2, 2) 'Remember arrays start at 0, so (1,1) means "B2", (1,0) means "A2")
End Sub
Function TwoDArr(file As String, Delim As String) As Variant
'This function open up a .csv or tabulatted .txt and parse it's info to an array
'It loop row by row (RowData) and in each Row, loops Column by Column (ColData) saving it's values
'in TempTwoDArr() which is then parsed to function request (TwoDArr)
'Adapted from https://stackoverflow.com/questions/12259595/load-csv-file-into-a-vba-array-rather-than-excel-sheet
Dim MyData As String, RowData() As String, ColData() As String
Dim TempTwoDArr() As Variant
Dim i As Long, n As Long
Open file For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
RowData() = Split(MyData, vbLf) 'for some reason RoodDatabase.txt only contain Linefeed character (No Carriage Return) and this will work on splitting other files too.
'RowData() = Split(MyData, vbCrLf) 'vbCrLf Chr( 13 ) + Chr( 10 ) Carriage return-linefeed combination
'source https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/miscellaneous-constants
Rs = UBound(RowData)
ReDim Preserve TempTwoDArr(Rs, 0)
For i = LBound(RowData) To UBound(RowData)
If Len(Trim(RowData(i))) <> 0 Then
ColData = Split(RowData(i), Delim)
'n = n + 1
ReDim Preserve TempTwoDArr(Rs, UBound(ColData))
For n = LBound(ColData) To UBound(ColData)
TempTwoDArr(i, n) = ColData(n)
Debug.Print ColData(n)
Next n
End If
Next i
TwoDArr = TempTwoDArr()
Debug.Print TempTwoDArr(2, 2)
Erase TempTwoDArr 'clear up memory
End Function
[编辑1]修改后的变量file
应该在第17行读为Path
[解决方案]修改了RowData() = Split(MyData, vbLf)
而不是RowData() = Split(MyData, vbCrLf)
'出于某种原因RoodDatabase.txt仅包含换行符(无回车符),并且由于此文件是在第三方软件中生成的,因此我无法控制超过它。
vBLf
也可以用于分割其他文件行。