0

我正在尝试隐藏/取消隐藏多个文本框,具体取决于在数据透视表切片器上选择的内容;

如果选择 UK,则显示 TextBox 21,但隐藏 TextBox 22 和 TextBox 23 如果选择 DE,则显示 TextBox 22,但隐藏 TextBox 21 和 TextBox 23 如果选择 FR,则显示 TextBox 23,但隐藏 TextBox 21 和 TextBox 22

我尝试录制一个宏来获取对象的命名约定,然后编写了下面的 VBA 代码,但它不起作用。谁能告诉我哪里出错了(我使用的是 Excel 2019);

Sub Changetextbox()
    If ActiveWorkbook.SlicerItems("UK").Selected = True Then
            ActiveSheet.Shapes.Range(Array("TextBox 21")).Visible = msoTrue
            ActiveSheet.Shapes.Range(Array("TextBox 22")).Visible = msoFalse
            ActiveSheet.Shapes.Range(Array("TextBox 23")).Visible = msoFalse
    If ActiveWorkbook.SlicerItems("DE").Selected = True Then
            ActiveSheet.Shapes.Range(Array("TextBox 21")).Visible = msoFalse
            ActiveSheet.Shapes.Range(Array("TextBox 22")).Visible = msoTrue
            ActiveSheet.Shapes.Range(Array("TextBox 23")).Visible = msoFalse
    If ActiveWorkbook.SlicerItems("FR").Selected = True Then
            ActiveSheet.Shapes.Range(Array("TextBox 21")).Visible = msoFalse
            ActiveSheet.Shapes.Range(Array("TextBox 22")).Visible = msoFalse
            ActiveSheet.Shapes.Range(Array("TextBox 23")).Visible = msoTrue
    End If
End Sub

任何帮助将非常感激。谢谢

4

1 回答 1

0

尝试这样的事情:

Sub Changetextbox()
    
    Dim si As SlicerItems, ws As Worksheet
    
    Set ws = ActiveSheet
    Set si = ActiveWorkbook.SlicerCaches("Slicer_ColA").SlicerItems ' edit to your slicer name
    
    ws.Shapes("TextBox 21").Visible = si("UK").Selected
    ws.Shapes("TextBox 22").Visible = si("FR").Selected
    ws.Shapes("TextBox 23").Visible = si("DE").Selected
    
End Sub

编辑:您可能需要检查切片器缓存的名称:

For Each sc In ActiveWorkbook.SlicerCaches
    Debug.Print sc.Name
Next sc
于 2021-01-13T18:18:08.427 回答