在另一个工作簿中运行相同的代码时,我遇到了解决类型不匹配的问题。可以说Workbook 1是原始工作簿,Workbook 2是新工作簿。
Workbook 1& 2具有相同的代码(下面)Listbox_Refresh
子调用GetAccountRef()
函数。代码在Workbook 1中运行良好,但在Workbook 2中类型不匹配,我无法弄清楚原因。
我检查了两个工作簿中GetAccountRef()
的 VarTypes ,但它们不同。
对于练习册1
这导致8204(vbArray + Variant)符合预期:
Debug.Print VarType(GetAccountRef())
这导致8(字符串)符合预期:
Debug.Print VarType(GetAccountRef(0))
对于练习册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
谢谢!
答案 0 :(得分: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") 'TFSA Tracker ONLY
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
Counter = Counter + 1
End If
Next Cell
GetAccountRef = Date_Ref '<~~ At this moved.
On Error GoTo 0
End Function
和你的图表模块
Sub test()
Dim ListedBnk As Variant
Dim myArray As Variant
myArray = GetAccountRef
With ActiveSheet
.ComboBox1.Clear
.ComboBox2.Clear
'For Each ListedBnk In GetAccountRef()
For Each ListedBnk In myArray
ListedBnk = Replace(ListedBnk, "9", "7")
.ComboBox1.AddItem Sheet5.Range(ListedBnk)
.ComboBox2.AddItem Sheet5.Range(ListedBnk)
Next ListedBnk
End With
End Sub
答案 1 :(得分:0)
发现我的错误,函数在不包含它的范围内查找标识符。感谢发表评论/解决方案的所有人!
改进是编写动态标识符,在添加行/列时调整范围。
功能:
Function GetAccountRef() As Variant
On Error Resume Next
Dim Cell As Range
Dim Row_I As Range
Set Row_I = Sheet5.Range(**"10:10"**) '<- previous range("9:9") did not contain the *identifier "Date"*, it was in row 10.
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
Sheet Sub:
With Activesheet
Dim ListedBnk As Variant
For Each ListedBnk In GetAccountRef()
ListedBnk = Range(Replace(ListedBnk, "10", "8")) '<- Also needs to refer to **Row 10**
.ComboBox1.AddItem ListedBnk
.ComboBox2.AddItem ListedBnk
Next ListedBnk
End With