2013-03-09 91 views
0

我使用從各個站點收集的代碼來讀取每個記錄都有分隔符的平面文件。代碼工作很好,除非文件中的記錄數超過505個時會產生運行時錯誤6錯誤。你能幫忙做些什麼嗎?我沒有VBA背景,但只是用來從其他的問題放在一起這個代碼的應用程序堆棧溢出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

名次比的WholeLine我猜的長度。使用一些Debug.Print語句在調試器中驗證或設置斷點 – rene 2013-03-09 21:44:54

回答

3

正在顯示錯誤6溢出你聲明NextPos作爲整型,它允許向上編號32768.如果InStr(返回的值高於此值,則會導致Overflow錯誤。

只需將數據類型更改爲Long,問題就會解決!

我還認爲你在Cells(ColNdx, RowNdx)中混合了參數 - 請注意,Cells預計該行作爲第一個參數,並且該列將作爲第二個參數!

BTW: 而不是你的文字的手動分裂的,你還可以使用內置的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