vba 从下拉框中返回选定的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9578038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 12:43:38  来源:igfitidea点击:

Return the selected text from a dropdown box

excelvbaexcel-vba

提问by karlstackoverflow

I am trying to return the text from a dropdown box that is selected on an Excel form. I have tried many things and the closest I have gotten is returning the index number. Also had a look at:

我正在尝试从 Excel 表单上选择的下拉框中返回文本。我尝试了很多东西,我得到的最接近的是返回索引号。还看了:

Link: Return the text from a dropdown box rather than the index number

链接:从下拉框中返回文本而不是索引号

I haven't found a working solution on that page. I have tried things such as:

我还没有在该页面上找到有效的解决方案。我尝试过以下事情:

ActiveSheet.DropDowns("DropDown1").Value
ActiveSheet.DropDowns("DropDown1").Text
ActiveSheet.DropDowns("DropDown1").SelectedValue
ActiveSheet.Shapes("DropDown1").Value

etc.

等等。

回答by chris neilsen

This will return the current selection from the DropDown

这将从 DropDown 返回当前选择

Sub TestDropdown()
    Dim ws As Worksheet
    Dim dd As DropDown

    Set ws = ActiveSheet
    Set dd = ws.Shapes("DropDown1").OLEFormat.Object

    MsgBox dd.List(dd.ListIndex)
End Sub

BTW, assigning to a variable declared as Dim dd As DropDownwill give you intellisense on dd

顺便说一句,分配给一个声明为的变量Dim dd As DropDown会给你智能感知dd

回答by cyberponk

You can also get the caller name, if the macro is called by the dropdown box itself. This way you don′t have to worry about renaming the dropdown boxes :)

如果宏由下拉框本身调用,您还可以获得调用者名称。这样你就不必担心重命名下拉框:)

Sub Dropdown_OnSelect()
    Dim dd As DropDown

    Set dd = ActiveSheet.Shapes(Application.Caller).OLEFormat.Object

    MsgBox dd.List(dd.ListIndex)
End Sub

回答by Niederee

If you are unable to Dim as DropDownI found that this alteration will work.

如果您不能,Dim as DropDown我发现此更改将起作用。

Sub TestDropdown()
    Dim ws As Worksheet
    Dim dd As Object

    Set ws = ActiveSheet
    Set dd = ws.DropDowns("DropDown1")

    MsgBox dd.List(dd.ListIndex)
End Sub