[英]I want to select data from a combo box and pull it through to my button using an IF statement in VBA Excel
我使用 VBA 在 Excel 中創建了一個組合框和按鈕。 我希望我的按鈕運行一個 IF 語句,並根據組合框中的選擇 go 到另一個工作表。 但是我當前的代碼在調試時給了我一個“需要對象”的錯誤。
請幫忙?
這是我當前的代碼:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.