簡體   English   中英

編譯錯誤:ByRef參數類型不匹配,我缺少什么?

[英]compile error: ByRef argument type mismatch, What am I missing?

我不明白問題是什么。

我有以下代碼:

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參數類型不匹配

我以為,如果我更新數組和函數的類型,那么它將起作用。

因此,我將Function更改為String,並將Brands()數組也更改為String。 然后我得到一個錯誤:

編譯錯誤:無法分配給數組

在行Brands() = GetTonerBrand(wsToner)SetupFormBrands() = GetTonerBrand(wsToner)

顯然我缺少了一些東西,只是看不到它是什么。

UPDATE

我看到了另一個名字相似的問題 ,但沒有幫助。

在對您的問題的評論中指出了一些要點,但沒有一個解決了以下事實: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變量類型變量來遍歷它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM