我正在尝试创建一个宏,该宏将允许我根据复选框删除列

I am trying to create a macro that will allow me to Delete columns based on a checkbox

提问人:alwayslearning 提问时间:10/4/2023 最后编辑:talleralwayslearning 更新时间:10/4/2023 访问量:27

问:

我正在尝试创建一个宏,允许我单击复选框,它们是动态的,因此总是会有不同数量的列和复选框(可以是 A:G,也可以是 A:AA)。

宏需要首先读取以查看 A 列中是否存在“TRUE”值,然后查看 B 列的值,然后将该文本值与第 1 行中的相应文本值匹配。 即,正在阅读,并且不会被删除,因为 A2 已被检查。

如果它没有“TRUE”值,则将删除与 B 列中相邻单元格匹配的相应列。 即,A3 中没有“TRUE”值,因此语法列被从行中删除。

附件是我的代码,我的电子表格的示例,以及我希望它在代码运行后的样子。

Sub Main_Routine()

Dim ws As Worksheet
Dim i As Integer
Dim lr As range
Dim lc As range
Dim rng As range
Dim FindString As String
Dim lCell As range

Set ws = ThisWorkbook.Worksheets("Result")

Set lr = range(Cells(1, 2), Cells(Rows.Count, 2).End(xlUp))

Set lc = ws.Cells.Find(What:="*", after:=ws.Cells(1, 1), LookIn:=xlFormulas, Lookat:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)

For i = lc.Column To 3 Step -1
    If ((Application.WorksheetFunction.CountIfs(ws.range("A:A"), "TRUE")) And (Application.WorksheetFunction.CountIfs(ws.range("B:B"), (Cells(lr, 2) = Cells(1, i).Value)))) Then
        Cells(1, i).EntireColumn.Hidden = False
    Else
        Cells(1, i).EntireColumn.Delete
    End If
Next i

End Sub

原始数据集

Original dataset

后宏数据集

Post Macro Dataset

Excel VBA IF-语句 复选框 countif

评论


答:

0赞 taller 10/4/2023 #1

假设所有复选框控件都与 A 列中的链接单元格相关联。应用白色字体颜色时,单元格列中的内容可能会变得不可见。

Option Explicit
Sub Main_Routine()
    Dim ws As Worksheet
    Dim i As Long, j As Long
    Dim lr As Long, lc As Long
    Dim arrData
    Set ws = ThisWorkbook.Worksheets("Result")
    ' Get the last row
    lr = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
    ' Get the last column
    lc = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
    ' Load data from column A:B
    arrData = ws.Range("A2:B" & lr).Value
    For i = lc To 3 Step -1
        For j = 1 To UBound(arrData)
            ' Subject matching
            If arrData(j, 2) = ws.Cells(1, i).Value Then
                ' Checkbox is checked
                If arrData(j, 1) Then ws.Columns(i).Delete
            End If
        Next
    Next i
End Sub

添加复选框或选项按钮

如何将复选框链接到单元格