下标超出了通话功能范围

时间:2016-10-24 18:32:25

标签: excel-vba call worksheet-function vba excel

我正在尝试根据工作表中存在哪些信息来填充ComboBox。此代码在模块的多个区域中重用,因此为了简单起见,我在调用函数中将其写出来。不幸的是,我在第If Worksheets("SheetName").Range("EG4") = "Current rate" Then行收到“下标超出范围”错误。我正在使用字符串SheetName来识别正确的工作表,并且它正确地捕获了名称。

有关为何可能发生此错误的任何建议表示赞赏。下面是我的代码的副本。

Sub FillComboBox(X As Integer)
Dim Combobox As String
Dim SheetName As String

With Application
    .DisplayAlerts = False
    .ScreenUpdating = False
End With

Combobox = "ComboBox" & CStr(X)
SheetName = "Scenario" & CStr(X)

    If Worksheets("SheetName").Range("EG4") = "Current rate" Then
        With ScenarioImport.Controls(Combobox)
        .ListIndex = 0
        End With
    ElseIf Worksheets("SheetName").Range("EG4") = "Current rate minus 1%" Then
        With ScenarioImport.Controls(Combobox)
        .ListIndex = 1
        End With
    ElseIf Worksheets("SheetName").Range("EG4") = "Current rate minus 2%" Then
        With ScenarioImport.Controls(Combobox)
        .ListIndex = 2
        End With
    ElseIf Worksheets("SheetName").Range("EG4") = "Primary rate" Then
        With ScenarioImport.Controls(Combobox)
        .ListIndex = 0
        End With
    ElseIf Worksheets("SheetName").Range("EG4") = "Secondary rate" Then
        With ScenarioImport.Controls(Combobox)
        .ListIndex = 1
        End With
    ElseIf Worksheets("SheetName").Range("EG4") = "Alternate rate" Then
        With ScenarioImport.Controls(Combobox)
        .ListIndex = 2
        End With
    ElseIf Worksheets("SheetName").Range("EG4") = "Sun Term - NA" Then
        With ScenarioImport.Controls(Combobox)
        .ListIndex = 0
        End With
    ElseIf Worksheets("SheetName").Range("EG4") = "Not applicable" Then
        With ScenarioImport.Controls(Combobox)
        .ListIndex = 0
        End With
    End If

End Sub

1 个答案:

答案 0 :(得分:0)

我找到了答案。我必须消除"SheetName"周围的引用,以便正确读取字符串并调用所需的工作表。想弄清楚的简单但令人沮丧的错误!