excel 组合框(窗体控件)中的宏在复制到另一个单元格后不起作用

axr492tv  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(179)

我是VBA新手。这个宏的想法是,一旦在第17行选择释放选项,第18行将基于图像隐藏。它工作正常,直到我试图将组合框复制到另一个单元格,在这个例子中,第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

我试着创建另一个组合框来测试它,并复制粘贴到另一个单元格,导致相同的结果。现在无法找出问题。感谢各种帮助!

uplii1fm

uplii1fm1#

根据组合框的类型,这里有三种方法。
使用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

相关问题