Excel ComboBox/formcontrol源单元格地址

tktrz96b  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(126)

我通过VBA从选定的单元格创建一个组合框下拉列表。如何通过VBA获取所选列表项(列表项源单元格)的地址(示例A1)?

ssgvzors

ssgvzors1#

开始了...这是其中一个模糊的东西。此处的ListFillRange属性用于嵌入在Shape("Drop Down 1")中的OLEObject

Sub FillComboRange()

    Dim Cb As Object
    Set Cb = ActiveSheet.Shapes("Drop Down 1").OLEFormat.Object
    Cb.ListFillRange = "D16:N30"
    Set Cb = Nothing
End Sub

如果你需要范围字符串,只需:

Sub GetComboRange()

    Dim Cb As Object, Str as String
    Set Cb = ActiveSheet.Shapes("Drop Down 1").OLEFormat.Object
    Str = Cb.ListFillRange

    MsgBox(Str)

    Set Cb = Nothing
End Sub

特别是对于所选单元格,地址可以由Cb.LinkedCell给出,阴影选项由Cb.Display3DShading给出

mkshixfv

mkshixfv2#

注意:我组织这段代码是为了解释,不是作为最佳实践的示例。

Function getSourceCellAddress(combobox_object as Object) as String

  ' get the name of the source range
    Dim name_of_dropdown_source as String
    name_of_dropdown_source = combobox_object.RowSource
  
  ' get the source range itself
    Dim dropdown_source_range as Range
    Set dropdown_source_range = Range(name_of_dropdown_source)
  
  ' get the current selected value
    Dim current_selected_value as String
    current_selected_value = combobox_object.Value

  ' get where in the list the selected item is located
    Dim row_index as Long
  ' two possible routes here: remove the one you don't need
    index = combobox_object.ListIndex ' if source doesn't have a heading row
    index = combobox_object.ListIndex + 1 ' if source has a heading row

  ' get name of source worksheet
    Dim worksheet_name as String
    worksheet_name = dropdown_source_range.Parent.name

  ' get the cell reference for the source data
    Dim address as String
    address = dropdown_source_range.Cells(row_index, 1).Address

  ' add the worksheet name and return the value
    getSourceCellAddress = worksheet_name & "!" & address
End Function

您可以在类似getSourceCellAddress(Table_Name.combobox_id)的情况下使用此函数。

相关问题