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

后端 未结 2 755
死守一世寂寞
死守一世寂寞 2021-01-14 10:02

I have the following VBA code (from MS Access 2007). The code creates a new workbook and adds a dropdown to a cell. This small snippet adds a drop down to a particular cell

2条回答
  •  [愿得一人]
    2021-01-14 10:22

    A few options.

    You could put a data validation drop down in the cell rather than a Dropdown object. This returns the actual results rather than the index. If you still need a separate linked cell, you can put a formula that simply copies the dv cell

    Sub MakeDv()
    
        Dim wSheet As Worksheet
        Dim myRng As Range
    
        Set wSheet = ActiveSheet
    
        Set myRng = wSheet.Cells(row, col)
        myRng.Validation.Add xlValidateList, , , "msg1,msg2"
        wSheet.Cells(row, col + 2).Formula = "=" & myRng.Address
    
    End Sub
    

    Another option is not to use the LinkedCell property and use a macro to write the value. Assign this macro the Dropdown

    Sub ShowDDResult()
    
        Dim dd As DropDown
    
        Set dd = ActiveSheet.DropDowns(Application.Caller)
    
        ActiveSheet.Cells(row, col + 2).Value = dd.List(dd.Value)
    
    End Sub
    

    That may not be so easy if you're creating the worksheet from scratch from Access because you'd have to add the macro. The final option is to use the ListFillRange property to fill the Dropdown. Put the list in a range and use a formula off of the LinkedCell to pull the date out of the list

    Sub testdd()
    
        Dim wSheet As Worksheet
        Dim myRng As Range
        Dim myDD As DropDown
        Dim rList As Range
        Dim aList(1 To 2, 1 To 1) As String
    
        Set wSheet = ActiveSheet
        Set rList = wSheet.Range("D1:D2")
    
        Set myRng = wSheet.Cells(row, col)
        aList(1, 1) = "msg1": aList(2, 1) = "msg2"
        rList.Value = aList
    
        With myRng
            Set myDD = .Parent.DropDowns.Add(Left:=.Left, Top:=.Top, Width:=.Width, Height:=.Height)
            myDD.ListFillRange = rList.Address
            myDD.LinkedCell = wSheet.Cells(row, col + 2).Address
            wSheet.Cells(row, col + 3).Formula = "=INDEX(" & rList.Address & "," & myDD.LinkedCell & ",1)"
        End With
    
    End Sub
    

提交回复
热议问题