我试图将一个空白数组传递给一个函数,该函数将根据某些场景操纵数组。我不知道我在哪里出错,但我收到以下错误Type mismatch
。下面显示了我如何创建空白数组:
Dim testArray(0 to 10) as string
Dim ABredu() As String
ABredu = Equipment(testArray)
下面显示了我为填充数组而编写的函数
Function Equipment(Test() As String)
If standYes = True And .ComboBox2.ListIndex = 0 Then
ReDim ABredu(1 To 3)
ABredu(1) = "Pen"
ABredu(2) = "Ruler"
ABredu(3) = "Monitor"
Else
ReDim ABredu(1 To 3)
ABredu(1) = "17-P2"
ABredu(2) = "17-L73"
ABredu(3) = "16-ENR"
End If
End sub
如果有人可以帮助我或推动正确的方向,我们将不胜感激!
答案 0 :(得分:3)
通过引用传递数组作为变体。
Function Equipment(ByRef Test As Variant)
If standYes = True And .ComboBox2.ListIndex = 0 Then
ReDim Test(1 To 3)
Test(1) = "Pen"
Test(2) = "Ruler"
Test(3) = "Monitor"
Else
ReDim Test(1 To 3)
Test(1) = "17-P2"
Test(2) = "17-L73"
Test(3) = "16-ENR"
End If
End sub
答案 1 :(得分:1)
使用变体数组的方法略有不同。
Sub Some_Macro()
Dim ABredu As Variant, i As Long
ABredu = Equipment(True, 0)
For i = LBound(ABredu) To UBound(ABredu)
Debug.Print ABredu(i)
Next i
ABredu = Equipment(False, 0)
For i = LBound(ABredu) To UBound(ABredu)
Debug.Print ABredu(i)
Next i
End Sub
Public Function Equipment(standYes As Boolean, cdLI As Long)
Dim vEQUIP As Variant
If standYes And cdLI = 0 Then
vEQUIP = Array("Pen", "Ruler", "Monitor")
Else
vEQUIP = Array("17-P2", "17-L73", "16-ENR")
End If
Equipment = vEQUIP
End Function
有几种方法可以实现您的目标。选择对你最有意义的那个。
答案 2 :(得分:0)
好的,所以我会在这里做一些关于你预期逻辑的假设,因为你问题中的代码有点荒谬。
你正在尝试(我认为):
考虑到这一点,您可以创建以下子
Sub PopulateEquipment(EquipArr() As String)
ReDim EquipArr(1 To 3)
If <condition> Then '<~~ Insert your own conditions here
EquipArr(1) = "Value 1"
EquipArr(2) = "Value 2"
EquipArr(3) = "Value 3"
Else
EquipArr(1) = "AltVal 1"
EquipArr(2) = "AltVal 2"
EquipArr(3) = "AltVal 3"
End If
End Sub
然后使用它填充数组,只需要Dim
,然后调用子例程,将变量作为参数传递。
Dim ABredu() As String
Call PopulateEquipment(ABredu)
答案 3 :(得分:0)
更简单,使用ArrayList。
Public arList As Object
Sub PartOne()
Set arList = CreateObject("System.Collections.ArrayList")
Call Equipment
End Sub
Private Sub Equipment() '// No Need to pass argument as arList is of Public scope.
With arList
If standYes And Me.ComboBox2.ListIndex = 0 Then
.Add "Pen"
.Add "Ruler"
.Add "Monitor"
Else
.Add "17-P2"
.Add "17-L73"
.Add "16-ENR"
End If
End With
End Sub