オプションのパラメーターとしてRangeを持つVBA関数を記述したいと思います。たとえば、次のようなものです。
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を取得しました!エラー。また、If(R)Then ... End Ifステートメント内にForループをラップしてみました。
オプションの範囲を処理する方法は何ですか?範囲が存在する場合、For Eachループを介して反復されますか?
回答:
回答№1は8これを試して
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から呼び出すことができます。
回答№2の場合は0
回避策:
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