我想从组合框中选择数据,然后使用VBA Excel中的IF语句将其拉到我的按钮上

问题描述

我使用VBA在Excel中创建了一个组合框和按钮。我希望我的按钮运行IF语句,并根据组合框中的选择转到其他工作表。但是我当前的代码在调试时给了我一个“需要对象”错误

请帮助?

这是我当前的代码

Sub Button9_Click()
    If DropDown13.Value = "Access Management" Then
        ThisWorkbook.Sheets("AccMA").Activate

    ElseIf DropDown13.Value = "Audit Management" Then
        ThisWorkbook.Sheets("AudMA").Activate

    ElseIf DropDown13.Value = "Asset Management" Then
        ThisWorkbook.Sheets("AssMA").Activate

    ElseIf DropDown13.Value = "Benefits Realisation" Then
        ThisWorkbook.Sheets("BenMA").Activate

    ElseIf DropDown13.Value = "Business Continuity Management" Then
        ThisWorkbook.Sheets("BCMA").Activate

    ElseIf DropDown13.Value = "Business Process Management" Then
        ThisWorkbook.Sheets("BPMA").Activate

    ElseIf DropDown13.Value = "Capacity Management" Then
        ThisWorkbook.Sheets("CAPA").Activate

    ElseIf DropDown13.Value = "Catalogue Management" Then
        ThisWorkbook.Sheets("CATA").Activate

    ElseIf DropDown13.Value = "Change Management" Then
        ThisWorkbook.Sheets("CNGA").Activate

    ElseIf DropDown13.Value = "Communications Management" Then
        ThisWorkbook.Sheets("COMA").Activate

    ElseIf DropDown13.Value = "Compliance Management" Then
        ThisWorkbook.Sheets("copA").Activate
    End If
End Sub

解决方法

您在dropdown13值和希望激活的图纸之间有一个已知的1:1关系。因此,通过使用Scripting.DIctionary,可以完全避免冗长而复杂的if / elseif。

Option Explicit

Dim mySheets As Scripting.Dictionary
   

Sub Button9_click()

Dim myValue As String

    myValue = dropdown13.Value
    
    If mySheets Is Nothing Then SetupMySheets
    
    If mySheets.Exists(myValue) Then
    
        ThisWorkbook.Sheets(mySheets.Item(myValue)).Activate
        
    Else
    
        'raise an error because the requested sheet doesn't exist
        
    End If
    
End Sub


Public Sub SetupMySheets()

    Set mySheets = New Scripting.Dictionary
    
    With mySheets
    
        .Add "Access Management","AccMA"
        .Add "Audit Management","AudMA"
        .Add "Asset Management","AssMA"
        .Add "Benefits Realisation","BenMA"
        .Add "Business Continuity Management","BCMA"
        .Add "Business Process Management","BPMA"
        .Add "Capacity Management","CAPA"
        .Add "Catalogue Management","CATA"
        .Add "Change Management","CNGA"
        .Add "Communications Management","COMA"
        .Add "Compliance Management","COPA"
        
    End With
    
    
End Sub
,

我认为您的核心问题是您在工作表上没有名为“ DropDown13”的控件。

一旦解决,则可以考虑使用Select Case而不是更详细的If ElseIf方法。

Sub Button9_Click()
    
    Select Case Me.DropDown13.Value
        Case "Access Management": sht = "AccMA"
        Case "Audit Management": sht = "AudMA"
        Case "Asset Management": sht = "AssMA"
        'etc etc
        Case Else: sht = ""
    End Select
    
    If Len(sht) > 0 Then ThisWorkbook.Sheets(sht).Activate

End Sub