【问题标题】:compile error: ByRef argument type mismatch, What am I missing?编译错误:ByRef 参数类型不匹配,我错过了什么?
【发布时间】:2017-11-15 02:29:49
【问题描述】:

我不明白问题出在哪里。

我有以下代码:

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 参数类型不匹配

我认为如果我更新数组和函数的类型,那么它会起作用。

所以我将函数更改为字符串,并将 Brands() 数组也更改为字符串。然后我得到一个错误:

编译错误:无法赋值给数组

SetupForm子线上Brands() = GetTonerBrand(wsToner)

显然我错过了一些东西,我只是不明白它是什么。

更新

我看到这个other question 有一个相似的名字,它没有帮助。

【问题讨论】:

  • GetTonerBrand 的最后一行应该是GetTonerBrand = Brands
  • 倒数第二行,应该是GetTonerBrand = Brands
  • GetTonerBrand 说它返回一个字符串,但你返回一个字符串数组,所以也改为As String()
  • 您似乎正在尝试将字符串分配给数组 (Brands() = GetTonerBrand(wsToner))。 Brands() 是一个数组,但你的函数只是一个字符串。

标签: vba excel excel-2016


【解决方案1】:

在 cmets 中对您的问题提出了很好的观点,但没有人解决 VBA 不会神奇地将您的字典键(Variant 数组)转换为 String 数组的事实。

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

'Parent nodes
Dim Brands() As Variant

在下面的代码中,请注意多余的变量已被删除,而剩余的变量则使用合适的类型声明。最后,为了返回值,函数的名称被分配给字典的键。

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

变体数组的一个很酷的地方是,您可以使用变体类型的变量迭代它们,只需一个简单的For Each

【讨论】:

    猜你喜欢
    • 2017-10-17
    • 1970-01-01
    • 2016-03-03
    • 2021-11-24
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多