将 ComboBox(表单控件)中的宏复制到另一个单元格中

问题描述 投票:0回答:1

这个宏的想法是,一旦在第17行选择了Release选项,第18行将根据图像隐藏。

它一直有效,直到我尝试将 ComboBox 复制到另一个单元格中,在本例中为第 23 行:

Sub ComboBox5_Change()
cb = ActiveSheet.Shapes("ComboBox5").TopLeftCell.row

With ActiveSheet.Shapes("ComboBox5")
    Cells(cb, 5) = .ControlFormat.List(.ControlFormat.ListIndex)
    If .ControlFormat.List(.ControlFormat.ListIndex) = "Courier" Then
        ActiveSheet.Range(Cells(cb + 1, 1), Cells(cb + 1, 1)).EntireRow.Hidden = False
    Else
        ActiveSheet.Range(Cells(cb + 1, 1), Cells(cb + 1, 1)).EntireRow.Hidden = True
    End If
End With
End Sub

我创建了另一个组合框来测试它,并将其复制/粘贴到另一个单元格,这导致了相同的结果。

excel vba combobox
1个回答
0
投票

根据您拥有的组合框类型,可以执行以下三种方法。

使用 ActiveX 控件:

Private Sub ComboBox1_Change()
    CB_ActiveX_Change Me.ComboBox1
End Sub

Private Sub ComboBox2_Change()
    CB_ActiveX_Change Me.ComboBox2
End Sub

Private Sub ComboBox3_Change()
    CB_ActiveX_Change Me.ComboBox3
End Sub

Public Sub CB_ActiveX_Change(cb As ComboBox)

    With cb.Parent
        'Cells returns a single cell range, no need to wrap in RANGE.
        '(cb.Value = "Courier") will return TRUE/FALSE which can be passed straight to the Hidden property of the control.
        .Cells(cb.TopLeftCell.Row + 1, 1).EntireRow.Hidden = (cb.Value = "Courier")
    End With
    
End Sub  

使用表单控件。将此宏分配给每个控件:

Public Sub CB_FormControl_Change()
    
    With Sheet1.Shapes(Application.Caller)
        .TopLeftCell.EntireRow.Hidden = (.ControlFormat.List(.ControlFormat.Value) = "Courier")
    End With

End Sub  

使用数据验证下拉列表:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Count = 1 Then
        If HasValidation(Target) Then
            Cells(Target.Row + 1, 1).EntireRow.Hidden = (Target.Value = "Courier")
        End If
    End If
End Sub

Public Function HasValidation(Cell As Range) As Boolean
    On Error Resume Next
        HasValidation = (Cell.Validation.Type = 3)
    On Error GoTo 0
End Function
© www.soinside.com 2019 - 2024. All rights reserved.