我在 excel 上,我有大约 30 个用户窗体复选框,每个复选框都位于一个大列中名为“摘要”的页面上。每一个都对应一个工作表。我正在尝试遍历这些复选框以查看哪些已勾选,哪些未勾选。我在所有工作表的循环中放置了一些代码,这是不起作用的位:
Private Sub Run_Click()
Dim SummaryFirstBlankRow As Integer
Dim LastRow As Integer
Dim LastRowH As Integer
Dim rng As Range
Dim SumOfHours As Variant
Dim EndLoop As Boolean
Dim DupeRowNo As Integer
Dim RowNo2 As Integer
Dim ClearContent As Boolean
Dim cbtrue As Boolean
Dim ws As Worksheet
cbtrue = False
For Each ws In ActiveWorkbook.Worksheets
LastRowH = ws.Cells(Rows.Count, 8).End(xlUp).Offset(1, 0).Row
'If ActiveWorkbook.Sheets("Summary").CheckBoxes(ws.name).Value = False Then ' looks to see if ws.names' checkbox is checked or not
' ClearContent = True 'if not checked, sets clear content to true
'End If
For Each CheckBox In Sheets("Summary").CheckBoxes
If CheckBox.name = ws.name Then
If CheckBox.Value = False Then
ClearContent = True
End If
End If
Next CheckBox
If ClearContent = True Then
For c = 1 To LastRowH 'if not checked, looks on current worksheet (within loop) and if any "Y" or "y" vals, clears them
If ws.Range("H" & c).Value = "Y" Or ws.Range("H" & c).Value = "y" Then
ws.Range("H" & c).ClearContents
End If
Next
End If
...
cbtrue 只是一个查看复选框是否存在的变量,因此如果存在,它将转到 if 语句,此时它将确定该复选框是否被勾选,根据此它保存 ClearContent 变量(我稍后在代码中使用)。
问题是当涉及到 'Shapes("ws.Name")' 时,ws.name 只是每个循环上工作表的名称。所以在循环的第一轮,它将是“摘要”......但是,我认为它正在物理上搜索显然不存在的工作表“ws.name”。我已经尝试从引号中删除它以及其他各种方法,例如 'Checkboxes("ws.Name")' 但似乎它们都有相同的问题。
我发帖是想看看是否有人可以为我提供另一种方法,或者可能告诉我哪里出错了,因为我认为我没有完全理解语法。
任何帮助表示赞赏。提前致谢 :)
更新
我在@Xabier 的帮助下更改了代码(我添加了一个额外的 if 语句以确保 CheckBox 与工作表具有相同的名称。我现在没有收到任何错误,但是当我运行它时,它不是清除我请求的任何单元格的内容。我似乎无法发现它为什么这样做,如果有人能发现它并告诉我,那就太好了。谢谢:)
最佳答案
您的代码有两个问题:
方面 1:名称还是文本?
我认为这里可能存在的问题是理解 Excel 中复选框的名称是什么:
您在复选框旁边看到的文本不是复选框的实际名称。您可以通过单击鼠标右键选择复选框并在左上角的选择名称框中输入所需的名称来为复选框命名。
使用此示例代码查看复选框实际使用的名称和显示文本:
For Each CheckBox In Sheets("Summary").CheckBoxes
MsgBox "Name: " & CheckBox.Name & " Text: " & CheckBox.Text
Next CheckBox
它会产生这样的东西:
如果我是正确的,要解决您的问题,您必须为复选框提供正确的名称(工作表的名称),或者不要比较
Name
, 比较使用 Text
复选框的属性。方面 2:值不是真/假
复选框的值不是
True
或 False
, 但复选框值可以是 xlOn
或 xlOff
.所以,不要测试 True
或 False
,但使用正确的常数。使用显示的文本而不是名称并使用正确的值常量的工作代码
Dim ws As Worksheet
Dim ClearContent As Boolean
Dim CheckBox As CheckBox
For Each ws In ActiveWorkbook.Worksheets
' Reset ClearContent for each Sheet
ClearContent = False
For Each CheckBox In Sheets("Summary").CheckBoxes
' Depending on your requests, compare either with Name or with Text
If CheckBox.Text = ws.Name Then
' Use xlOff constant instead of False
If CheckBox.Value = xlOff Then
ClearContent = True
End If
' We can exit the foreach loop when we found the correct checkbox
Exit For
End If
Next CheckBox
If ClearContent Then
MsgBox "Going to clear " & ws.Name
End If
Next ws
关于vba - 动态检查与 Worksheets -VBA Excel 同名的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52183404/