我在解决类型不匹配时遇到问题,当在不同的工作簿中运行相同的代码时。让我们说练习册1是原始练习册,练习册2是新练习册。VBA类型不匹配在不同的工作簿中相同的功能
这两个工作簿1 & 2具有相同的代码(下面)Listbox_Refresh
子调用GetAccountRef()
函数。该代码在工作簿1中运行良好,但在工作簿2中存在类型不匹配,我无法弄清楚原因。
我检查了两个工作簿中的VarTypes的GetAccountRef()
,它们是不同的。
对于工作簿1
这导致8204(的VBArray +变型)如预期:
Debug.Print VarType(GetAccountRef())
这导致8(字符串)如预期:
Debug.Print VarType(GetAccountRef(0))
For Workbook 2
这导致0(空):
Debug.Print VarType(GetAccountRef())
这导致错误类型不匹配:
Debug.Print VarType(GetAccountRef(0))
我试图运行的函数是:
Function GetAccountRef() As Variant
On Error Resume Next
Dim Cell As Range
Dim Row_I As Range
Set Row_I = Sheet5.Range("9:9") '<- ERROR: This range does not contain "Date"
Dim Counter As Integer
Counter = 0
Dim Date_Ref() As Variant
For Each Cell In Row_I
If Cell = "Date" Then
ReDim Preserve Date_Ref(Counter)
Date_Ref(Counter) = Cell.Address
GetAccountRef = Date_Ref
Counter = Counter + 1
End If
Next Cell
On Error GoTo 0
End Function
和我想要使用此功能在For
循环,像这样:
Dim ListedBnk As Variant
For Each ListedBnk In GetAccountRef()
ListedBnk = Replace(ListedBnk, "9", "7")
.ComboBox1.AddItem Range(ListedBnk)
.ComboBox2.AddItem Range(ListedBnk)
Next ListedBnk
谢谢!
取下上的错误继续下一步 - 在那里,它是如何失败? –
由于GetAccountRef的值最终从Row_I范围绘制,我怀疑该范围在Workbook2中为空。无论如何,我同意上面的评论,应该删除错误陷印,并且应该逐步浏览代码,以确切地查看它失败的位置。 –
@TonyM是的,这的确是这样,希望我早点看到您的评论! – AnthonyT