我有一個字符串數組:如何在陣列上使用每個循環?
Dim sArray(4) as String
我通過陣列中的每個字符串去:
for each element in sarray
do_something(element)
next element
do_something
以一個字符串作爲參數
我得到一個錯誤的傳球作爲字符串的元素:
ByRef Argument Mismatc h
我應該將元素轉換爲String還是其他?
我有一個字符串數組:如何在陣列上使用每個循環?
Dim sArray(4) as String
我通過陣列中的每個字符串去:
for each element in sarray
do_something(element)
next element
do_something
以一個字符串作爲參數
我得到一個錯誤的傳球作爲字符串的元素:
ByRef Argument Mismatc h
我應該將元素轉換爲String還是其他?
元素必須是一個變體,所以你不能把它聲明爲一個字符串。你的函數應該接受一個變體,如果它是一個字符串,只要你通過它的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
另一種選擇是在傳遞變量之前將變體轉換爲字符串。
do_something CStr(element)
我給這個答案加了一票,因爲這實際上是被問到的,但我覺得這個相關的參考也值得一提:https://support.microsoft.com/en-us/kb/129931 – 2015-05-12 14:52:27
由於sArray是空的,這將不會執行任何操作?!?! – Black 2016-11-10 09:16:03
@EdwardBlack - 他只給出與討論相關的代碼片段。據推測,sArray和For Each循環的尺寸之間的附加代碼實際上會定義它。但是如何定義這個問題並不重要。 – 2017-01-24 20:43:59
針對每個循環結構的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
+一,LBound和UBound的使用很清楚!雖然另一種選擇是使用For Each塊.. – SIslam 2016-03-11 09:02:17
我使用像Fink建議的計數器變量。如果你想爲每通過爲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
你看這個簡單的inArray函數的字符串:
Function isInArray(ByVal stringToBeFound As String, ByVal arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
聽起來像你的do_something簽名具有byref指定,但它應該是byval而不是? – CarneyCode 2010-11-19 18:36:22