更改Dim语句的位置时出现ByRef参数类型不匹配错误

时间:2018-08-09 15:12:22

标签: excel-vba

Dim rangeStr, dataRow, bomRow, levelRow, sNewSheetName, quantRow As String
Dim y, desc, endcap As String
If SheetExists(sNewSheetName) Then
    Application.DisplayAlerts = False
    ThisWorkbook.Sheets(sNewSheetName).Delete
    Application.DisplayAlerts = True
End If

Private Function SheetExists(sheetToFind As String) As Boolean
    Dim sSheet As Worksheet

    SheetExists = False
    For Each sSheet In Worksheets
        If sheetToFind = sSheet.Name Then
            SheetExists = True
            Exit For
        End If
    Next sSheet   
End Function

If语句的第三行引发错误。我有解决问题的方法,但是我想了解为什么会起作用。如果我只是将 quantRow 变量向下移动到第二个dim语句,则代码是无错误的,因此第一行以 sNewSheetName As String 结尾。似乎在Dim语句的 sNewSheetName 前面添加了一个变量,使该错误出现,并且我很想知道为什么。

1 个答案:

答案 0 :(得分:4)

您误解了Dim声明。

Dim blah, blah2, blah3 As String

Blah3被声明为String。前两个是变体。

当您向下移动quantRow时,sNewSheetName被声明为String,它可以正常工作。在移动quantRow之前,sNewSheetName被声明为Variant,并且在检查SheetExists()时下标不喜欢它,因为它期望String Variant

Private Function SheetExists(sheetToFind As **String**) As Boolean

Dim几个项目没有声明为变体的正确方法是:

Dim blah as String, blah2 as String, blah3 as String