2017-10-20 58 views
0

我有以下功能找到電子表格中有數據的最後一列,我得到一個運行時錯誤28.我相信它並沒有正常退出我的for循環。我錯過了一些愚蠢的東西嗎?我已經完成了多個簡單的功能,完全沒有問題。我不知道它現在退出我的for循環,我得到運行時錯誤28

Function max_column() 

Dim i As Integer 
Dim max_col As Integer 

For i = 1 To 200 
If Worksheets("Sheet1").Cells(2, i) = "" Then max_col = i: Exit For 
Next i 
max_column() = max_col 
Exit Function 
End Function 
+0

從'if'語句中刪除'max_col = i:'(注意冒號也被刪除)...將第3行從結尾更改爲'max_column()= i' ....刪除'Exit Function' .. 。刪除'Dim max_col As Integer' – jsotola

回答

1

有這裏發生了一些事情。首先,你應該避免使用Integers而不是Longs。指定Integer的值大於32,767。如果你試圖給它一個32,768的值,你將得到一個運行時Overflow錯誤(錯誤編號8)。

修復該第一位應該是這樣的:

Function max_column() 

    Dim i As Long 
    Dim max_col As Long 

    For i = 1 To 200 
    If Worksheets("Sheet1").Cells(2, i) = "" Then max_col = i: Exit For 
    Next i 
    max_column() = max_col 
    Exit Function 
End Function 

當然,這並不解決問題,它只是擺脫一個常見的錯誤,往往會導致問題。在這裏有一些更加險惡的事情可能是問題。首先,您正在使用不合格的Worksheets參考,這意味着您依賴於ActiveWorkbook,無論這是否是預期的目標。

第二個問題是:字符。這表示一個換行符,實際上並沒有換行符!多麼方便......除非你錯過了你的邏輯問題。

For i = 1 To 200 
    If Worksheets("Sheet1").Cells(2, i) = "" Then max_col = i: Exit For 
Next i 

是真的:

For i = 1 To 200 
    If Worksheets("Sheet1").Cells(2, i) = "" Then 
     max_col = i 
    End If 

    Exit For 
Next i 

所有這個循環將永遠做的是返回1或0,因爲無論是第二行中的第一個單元格爲空,或者退出循環。

最後,你的函數返回調用再次被調用,這是造成堆棧溢出錯誤(因爲它保持調用和調用和調用....)。

修復max_colum真的應該是GetTheFirstColumnOnTheActiveSheetThatHasANullStringValueInTheSecondRow(請注意,實際功能不是簡單的max_column)。

有了這些改變你的代碼變成:

Function max_column() 
    Dim i As Long 
    Dim max_col As Long 

    For i = 1 To 200 
     If Worksheets("Sheet1").Cells(2, i) = "" Then 
      max_col = i 
      Exit For 
     End If 
    Next i 

    max_column = max_col 

    Exit Function 
End Function 

並與最後的調整,以避免其他錯誤:

Public Function GetMaxColumn() as Long 
    Dim i As Long 
    For i = 1 To 200 
     If ActiveWorkbook.Worksheets("Sheet1").Cells(2, i) = vbNullString Then 
      GetMaxColumn = i 
      Exit Function 
     End If 
    Next i 
End Function 

瞧!一個完美的功能函數。

+0

非常有意義。我有非常不好的習慣,我需要打破。 – user3865990

0

我會稍微修改您的If聲明。

Function max_column() 

Dim i As Integer 
Dim max_col As Integer 

For i = 1 To 200 
    If Worksheets("Sheet1").Cells(2, i) = "" Then 
    max_col = i 
    Exit For 
    Else 
    End If 
Next i 

max_column() = max_col 

End Function 

希望這有助於!

+0

謝謝!我現在看到我的退出語句實際上並不在我的循環中。 – user3865990

1

不需要循環,只需使用END()。

這將在第2行返回第一個空白單元格:

Function max_column() as Long 
    If Worksheets("Sheet1").Cells(2, 1) = "" Then 
     max_column = 1 
    Else 
     max_column = Worksheets("Sheet1").Cells(2, 1).End(xlToRight).Column + 1 
    End If 
End Function 

如果你想要的是列正好在行使用上次使用的電池:

Function max_column() as Long 
    max_column = Worksheets("Sheet1").Cells(2, Worksheets("Sheet1").Columns.Count).End(xlToLeft).Column + 1 
End Function 
+0

如果'Cells(2,1)'的值是'vbNullString',那麼End命令的工作方式與OP的功能不同。 –

+0

@BrandonBarney true,fixed。請參閱編輯。 –

+0

@BrandonBarney仍然不需要循環。 –

相關問題