我使用从各个站点收集的代码来读取一个平面文件,该文件具有每个记录的分隔符。代码工作得很好,除非文件中的记录数超过505,否则会出现运行时错误6错误。你能帮忙解决这个问题吗?我没有VBA背景,但只是使用了其他人的问题来为应用程序整理这段代码
Sub Posting()
Dim RowNdx As Long
Dim ColNdx As Integer
Dim TempVal As Variant
Dim WholeLine As String
Dim Pos As Integer
Dim NextPos As Integer
Dim SaveColNdx As Integer
Dim FName As String
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.ClearContents
Range("A1").Select
Application.ScreenUpdating = False
'On Error GoTo EndMacro:
Sep = "@"
FName = Application.GetOpenFilename
If sFileName = "False" Then Exit Sub
Cells(1, 8).Value = Mid(FName, Len(FName) - 8, 4)
SaveColNdx = ActiveCell.Column
RowNdx = ActiveCell.Row
Open FName For Input Access Read As #1
While Not EOF(1)
Line Input #1, WholeLine
If Right(WholeLine, 1) <> Sep Then
WholeLine = WholeLine & Sep
End If
ColNdx = SaveColNdx
Pos = 1
NextPos = InStr(Pos, WholeLine, Sep)
While NextPos >= 1
TempVal = Mid(WholeLine, Pos, NextPos - Pos)
Cells(ColNdx, RowNdx).Value = TempVal
Pos = NextPos + 1
ColNdx = ColNdx + 1
NextPos = InStr(Pos, WholeLine, Sep)
Wend
RowNdx = RowNdx + 1
Wend
NextPos = InStr(Pos, WholeLine, Sep)
答案 0 :(得分:3)
您将NextPos
声明为Integer,允许编号为32768.如果InStr(
返回的值高于此值,则会导致Overflow
错误。
只需将数据类型更改为Long
,您的问题就会得到解决!
我还认为你在Cells(ColNdx, RowNdx)
混合了参数 - 请注意,Cells
期望行为第一个参数,列为第二个!
顺便说一句:
您也可以使用内置的Split
函数:
Dim varSplitted as Variant
...
While Not EOF(1)
Line Input #1, WholeLine
varSplitted = Split(WholeLine, Sep)
Range(RowNdx,SaveColNdx).Resize(, UBound(varSplitted, 1)+1) = varSplitted
RowNdx = RowNdx + 1
Wend