有這裏發生了一些事情。首先,你應該避免使用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
瞧!一個完美的功能函數。
從'if'語句中刪除'max_col = i:'(注意冒號也被刪除)...將第3行從結尾更改爲'max_column()= i' ....刪除'Exit Function' .. 。刪除'Dim max_col As Integer' – jsotola