【发布时间】:2020-06-11 16:54:29
【问题描述】:
我有这段代码可以在输出到 Excel 工作表之前传输一个逗号分隔的文本文件,其中的行和列与文本文件中一样,但是在此行上的大 txt 文件大小上出现下标超出范围错误DataOut(RowCnt, cnt) = Line(cnt)
Sub DelimitedTextFileToArray()
Dim ColCnt As Long
Dim cnt As Long
Dim DataIn() As Byte
Dim DataOut As Variant
Dim Delimiter As String
Dim File As String
Dim Line As Variant
Dim Lines As Variant
Dim RngOut As Range
Dim RowCnt As Long
Dim Text As String
Dim Wks As Worksheet
' // Use the ActiveSheet. You specifiy any sheet you want here.
Set Wks = ActiveSheet
' // Starting cell for output.
Set RngOut = Wks.Range("A1")
File = "C:\jmp\P428520200530.txt"
' // Character that separates the data fields.
Delimiter = ","
' // Read the whole file into memory as byte data.
Open File For Binary Access Read As #1
ReDim DataIn(LOF(1))
Get #1, , DataIn
Close #1
' // Find the rows and the greastest column width needed for the transpose array.
For n = 0 To UBound(DataIn, 1) - 1
' // Is this byte a delimiter?
If DataIn(n) = Asc(Delimiter) Then cnt = cnt + 1 ' Count the number of columns in this line.
'// Is this the end of the line?
If DataIn(n) = 13 Then
' // Save the greatest number of columns found.
If cnt > ColCnt Then ColCnt = cnt
cnt = 0 ' Reset the line column count.
RowCnt = RowCnt + 1 ' Increase the row count.
End If
Next n
' // Convert the bytes into a string.
Text = StrConv(DataIn, vbUnicode)
' // Create an array of the lines.
Lines = Split(Text, vbCrLf)
' // Dimension the transpose array.
ReDim DataOut(ColCnt, RowCnt)
' // fill the transpose array.
For RowCnt = 0 To UBound(DataOut, 2) - 1
Line = Split(Lines(RowCnt), Delimiter)
For cnt = 0 To UBound(Line)
DataOut(RowCnt, cnt) = Line(cnt)
Next cnt
Next RowCnt
' // Output the array to the worksheet.
RngOut.Resize(ColCnt + 1, RowCnt + 1).Value = DataOut
End Sub
【问题讨论】:
-
我要做的第一件事是检查我的变量的值是多少?当错误发生时,检查变量代表什么。这也是用
vba或vbscript写的——它们不一样,请适当地编辑你的标签。 -
看起来
ReDim DataOut(ColCnt, RowCnt)和DataOut(RowCnt, cnt) = Line(cnt)之间不匹配。