[英]Excel VBA - Using Ranges as Optional parameters for functions?
我想寫一個VBA函數,它有一個Range作為可選參數。 例如:
Public Function testfunc(S As String, Optional R As Range) As String
testfunc = S
For Each cell In R
testfunc = testfunc + cell
Next cell
End Function
我嘗試了上面的功能,但我得到了一個#VALUE! 錯誤。 我還嘗試在For(R)Then ... End If語句中包裝For循環。
什么是處理可選范圍的方法,如果范圍存在,那么它是通過For Each循環迭代的?
試試這個
Public Function testfunc(S As String, Optional R As Range = Nothing) As String
testfunc = S
if not R is nothing then
For Each cell In R
testfunc = testfunc & cell
Next cell
end if
End Function
我已經在Excel 2007中測試了這個。你需要將它放入模塊,而不是工作表或工作簿代碼部分。 然后可以從帶有或不帶Range對象的VBA調用該函數,或者作為工作表函數調用該函數。
解決方法:
Public Function testfunc(S As String, Optional R As String = vbNullString) As String
testfunc = S
If R <> vbNullString Then
For Each cell In Range(R)
' & for concatenation not + '
testfunc = testfunc & cell
Next cell
End If
End Function
Sub test()
MsgBox testfunc("", "A1:A5"), vbOKOnly, "Results"
MsgBox testfunc(""), vbOKOnly, "Results"
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.