【问题标题】:Why does this not create a combobox?为什么这不创建一个组合框?
【发布时间】:2021-04-11 04:38:24
【问题描述】:
Sub Auto_Open()
Dim ComboBox2 As Object
Dim ws As Worksheet
Dim rng As Range
Const cCount As Long = 2

Set ws = ActiveSheet(1)

With ws
    Set rng = .Range("H10")

    Set ComboBox2 = .Shapes.AddFormControl(xlDropDown, _
                                          Left:=rng.Left, _
                                          Top:=rng.Top, _
                                          Width:=rng.Width, _
                                          Height:=rng.Height)
With ComboBox2
        .ControlFormat.DropDownLines = 100
        .Name = "myCombo"
End With
With Worksheets(5)
    Dim erg As Range: Set erg = .Range("D6", .Range("D" & .Rows.Count) _
        .End(xlUp)).Resize(, cCount)
    Worksheets(1).ComboBox2.ColumnCount = cCount
    Worksheets(1).ComboBox2.List = erg.Value
End With
End Sub

此代码在工作簿中。 当有人打开此文件然后从工作表 5 填充它时,我正在尝试创建一个组合框。 它没有发生,没有创建任何内容,我也没有收到任何错误。

【问题讨论】:

  • 我更新了原帖。
  • 您是手动打开工作簿还是通过代码打开工作簿?另外,您将此代码放在哪里?如果代码放置在模块中并手动打开,则 Auto_Open 将起作用,否则它将不起作用,因此建议在 thisworkbook 模块中使用 Workbook_Open。如果Auto_Open 会运行,您将在Set ws = ActiveSheet(1) 上遇到错误:)

标签: excel vba combobox


【解决方案1】:

尝试使用 Workbook_Open 事件而不是 Auto_Open 事件(它的存在是为了向后兼容),代码应该放在 ThisWorkbook 对象中。

Private Sub Workbook_Open()
    Dim ComboBox2 As Object
    Dim ws As Worksheet
    Dim rng As Range
    Const cCount As Long = 2
    
    Set ws = ActiveSheet 'Avoid using ActiveSheet, replace this with the worksheet name instead
    
    With ws
        Set rng = .Range("H10")
    
        Set ComboBox2 = .Shapes.AddFormControl(xlDropDown, _
                                              Left:=rng.Left, _
                                              Top:=rng.Top, _
                                              Width:=rng.Width, _
                                              Height:=rng.Height)
    End With
    
    With ComboBox2
            .ControlFormat.DropDownLines = 100
            .Name = "myCombo"
    End With
    
    With Worksheets(5)
        Dim erg As Range
        Set erg = .Range("D6", .Range("D" & .Rows.Count) _
                    .End(xlUp)).Resize(, cCount)
    End With
    
    With Worksheets(1).ComboBox2
        .ColumnCount = cCount
        .List = erg.Value
    End With
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    相关资源
    最近更新 更多