我有一个字符串数组:
Dim sArray(4) as String
Run Code Online (Sandbox Code Playgroud)
我将遍历数组中的每个String:
for each element in sarray
do_something(element)
next element
Run Code Online (Sandbox Code Playgroud)
do_something 将字符串作为参数
我收到错误传递元素作为字符串:
ByRef Argument Mismatch
我应该将元素转换为String还是其他什么?
小智 105
元素需要是变体,因此您不能将其声明为字符串.只要你传递ByVal,你的函数应该接受一个变量,如果它是一个字符串.
Public Sub example()
Dim sArray(4) As string
Dim element As variant
For Each element In sArray
do_something (element)
Next element
End Sub
Sub do_something(ByVal e As String)
End Sub
Run Code Online (Sandbox Code Playgroud)
另一种选择是在传递变量之前将变换转换为字符串.
do_something CStr(element)
Run Code Online (Sandbox Code Playgroud)
Fin*_*ink 37
每个循环结构的A更多地围绕集合对象设计.For..Each循环需要变体类型或对象.由于您的"元素"变量被输入为变体,因此"do_something"函数需要接受变体类型,或者您可以将循环修改为以下内容:
Public Sub Example()
Dim sArray(4) As String
Dim i As Long
For i = LBound(sArray) To UBound(sArray)
do_something sArray(i)
Next i
End Sub
Run Code Online (Sandbox Code Playgroud)
我像Fink建议的那样使用计数器变量.如果你想要For Each并传递ByRef(对于长字符串可以更有效),你必须使用CStr将你的元素转换为字符串
Sub Example()
Dim vItm As Variant
Dim aStrings(1 To 4) As String
aStrings(1) = "one": aStrings(2) = "two": aStrings(3) = "three": aStrings(4) = "four"
For Each vItm In aStrings
do_something CStr(vItm)
Next vItm
End Sub
Function do_something(ByRef sInput As String)
Debug.Print sInput
End Function
Run Code Online (Sandbox Code Playgroud)
这个简单的 inArray 函数怎么样:
Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
390017 次 |
| 最近记录: |