编译错误:ByRef参数types不匹配,我错过了什么?

我不明白是什么问题。

我有以下代码:

Public Sub SetupForm() Dim wbMain As Workbook Dim wsToner As Worksheet Set wbMain = ActiveWorkbook Set wsToner = wbMain.Sheets("Toner") With DashboardForm 'Parent nodes Dim Brands() As String Brands() = GetTonerBrand(wsToner) 

最后一行是调用以下函数:

 Private Function GetTonerBrand(wsSheet As Worksheet) As String Dim col, Counter Dim LastCol Counter = 0 Dim LastRow Dim Brands() As String With wsSheet LastRow = .Cells(.Rows.Count, 2).End(xlUp).Row Dim RowCount RowCount = LastRow End With Dim dict Set dict = CreateObject("Scripting.Dictionary") Do While RowCount > 3 If Not dict.exists(wsToner.Cells(RowCount, 2).Value) Then dict.Add wsToner.Cells(RowCount, 2).Value, 0 End If RowCount = RowCount - 1 Loop ReDim Brands(0 To dict.Count) Brands() = dict.keys() GetTonerBrand Brands End Function 

当我尝试运行这个我得到下面的错误:

编译错误:ByRef参数types不匹配

我认为,如果我更新数组的types和function,那么它会工作。

所以我把函数改成String,而Brands()数组也改为String。 然后我得到一个错误:

编译错误:不能分配给数组

Brands() = GetTonerBrand(wsToner)上的SetupForm子版中,

Obviouly我失去了一些东西,我只是不知道它是什么。

UPDATE

我以类似的名字看到了这个其他的问题 ,这是没有帮助的。

在你的问题的评论中提到了好的观点,但是没有一个提到VBA不会将你的字典密钥Variant数组转换为String数组。

我build议你修改你的函数来返回一个Variant数组。 在你的调用代码中,你必须修改你的声明:

 'Parent nodes Dim Brands() As Variant 

在下面的代码中,请注意,superflousvariables被淘汰,而剩下的variables被声明为合适的types。 最后,要返回值,函数的名称将被分配字典的键。

 Private Function GetTonerBrand(wsSheet As Worksheet) As Variant() Dim row As Long Dim tonerBrands As Object Dim tonerBrand As String With wsSheet row = .Cells(.Rows.Count, 2).End(xlUp).row End With Set tonerBrands = CreateObject("Scripting.Dictionary") Do While row > 3 tonerBrand = CStr(wsToner.Cells(row, 2).Value) If Not tonerBrands.Exists(tonerBrand) Then tonerBrands.Add tonerBrand, 0 End If row = row - 1 Loop GetTonerBrand = tonerBrands.Keys() End Function 

关于变体数组的一个很酷的事情是,你可以使用变体types的variables遍历它们,并且使用一个简单的For Each