0

我使用从各个站点收集的代码来读取每个记录都有分隔符的平面文件。该代码运行良好,除非文件中的记录数超过 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

运行时错误 6 溢出显示在NextPos = InStr(Pos, WholeLine, Sep)

4

1 回答 1

3

您声明NextPos为整数,允许将 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
于 2013-03-09T21:45:14.060 回答