简体   繁体   English

从下拉列表中选择值时可以调用宏吗?

[英]can you call a macro when selecting a value from a dropdown list?

I have an excel spreadsheet with a dropdown list (AH,AR, CH etc).我有一个带有下拉列表(AH、AR、CH 等)的 Excel 电子表格。 Dependent on the value selected in the drop down the values on the sheet change which are a series of vlookups.根据下拉列表中选择的值,工作表上的值会发生变化,这是一系列的查找。 Some of these return blank rows and i have a macro that hides the rows if they are blank.其中一些返回空白行,我有一个宏可以隐藏这些行,如果它们是空白的。

Is there a way that i can assisgn the macro to the drop down so that the macro is called on click.有没有办法可以将宏分配给下拉列表,以便在单击时调用宏。

You need to access that particular worksheet module, which you can do by right clicking on the sheet name and selecting view code .您需要访问该特定的工作表模块,您可以通过右键单击工作表名称并选择查看代码来执行此操作 At this point you need to use a Worksheet_Change sub something like below, which will run code when the value of cell A1 is changed此时,您需要使用Worksheet_Change子项,如下所示,当单元格A1的值更改时,它将运行代码

Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("A1")) Is Nothing Then
        Select Case Target.Value
            Case "DropdownValue1"
               'do something
            Case "DropdownValue2"
                'do something else
        End Select 
    End If
End Sub

You can assign macros to the Worksheet.Change event and add a condition that runs a specific macro based on the value.您可以将宏分配给Worksheet.Change事件,并添加一个基于该值运行特定宏的条件。

For example:例如:

Private Sub Worksheet_Change(ByVal Target as Range) 

If Not Intersect(Target, Thisworkbook.Sheets("WorksheetName").Range("AH")) Is Nothing 
    If Target.Value = "DropdownValue1" Then
        Macro1
    Elseif Target.Value = "DropdownValue2" Then
        Macro2
    Elseif Target.Value = "DropdownValue3" Then
        Macro3
    End if
End if

End Sub

Try to modify below code:尝试修改以下代码:

 Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("E1")) Is Nothing Then
        Select Case Range("E1")
            Case "Insert Blank rows": Macro1
            Case "Hide All Sheets": Macro2
            Case "Convert to Date": Macro3
        End Select
    End If
End Sub

Ref: https://www.extendoffice.com/documents/excel/4421-excel-run-macro-from-drop-down-list.html参考: https : //www.extendoffice.com/documents/excel/4421-excel-run-macro-from-drop-down-list.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM