如何获取已勾选CheckBox所在单元格的行号?现有VBA代码无法运行
获取勾选状态CheckBox的所在行号
你想要获取处于勾选状态(xlOn)的CheckBox所在单元格的行号,但当前VBA代码无法正常运行,你的代码如下:
Dim checkNums As Variant checkNums = Array(1, 5, 6, 7, 10, 11, 12, 14, 15, 16, 17, 18, 50, 51) For k = LBound(checkNums) To UBound(checkNums) Set FoundCell = s2.Range("C:C").Find(What:=(s2.CHECKBOXES("Check Box " & checkNums(k)).Value = xlOn)) If Not FoundCell Is Nothing Then Debug.Print (" found in row: ") & FoundCell.Row Else Debug.Print ("Found") End If
你的代码逻辑完全错误:Range.Find是用来查找单元格内的内容(比如文本、数值),但你把“CheckBox是否勾选”的布尔判断结果传给了What参数,这根本不符合Find的使用场景,自然得不到正确结果。
直接用CheckBox对象自带的TopLeftCell属性就能获取它所在的单元格,进而拿到行号,修改后的代码如下:
Dim checkNums As Variant Dim chkBox As CheckBox checkNums = Array(1, 5, 6, 7, 10, 11, 12, 14, 15, 16, 17, 18, 50, 51) For k = LBound(checkNums) To UBound(checkNums) Set chkBox = s2.CheckBoxes("Check Box " & checkNums(k)) ' 判断CheckBox是否处于勾选状态 If chkBox.Value = xlOn Then ' 直接获取CheckBox所在单元格的行号 Debug.Print "勾选的CheckBox所在行号: " & chkBox.TopLeftCell.Row Else Debug.Print "该CheckBox未勾选" End If Next k
额外说明
- 如果你的CheckBox是通过
LinkedCell关联到某个单元格的,想要获取关联单元格的行号,可以改用:Range(chkBox.LinkedCell).Row - 确保代码里的
s2是已正确赋值的工作表对象,避免因对象引用错误导致代码报错。
内容的提问来源于stack exchange,提问作者wasif ahmed
相关产品推荐
相关产品推荐

