使用VBA系统地定义一组复选框(excel)的链接单元格
在电子表格中,我有大量预先存在的复选框,手动设置每个复选框的链接单元格将是一项繁琐的任务 我希望将大量的代码组合在一起,然后编写VBA代码,以实现:使用VBA系统地定义一组复选框(excel)的链接单元格,excel,vba,Excel,Vba,在电子表格中,我有大量预先存在的复选框,手动设置每个复选框的链接单元格将是一项繁琐的任务 我希望将大量的代码组合在一起,然后编写VBA代码,以实现: i = 1 n = number of checkboxes in group While i < n Loop For checkbox i in 'group X', assign linked cell to cell (range A1-->Z1) End loop i=1 n=组中的复选框数 而我 环 对于“组X”中的复选框
i = 1
n = number of checkboxes in group
While i < n
Loop
For checkbox i in 'group X', assign linked cell to cell (range A1-->Z1)
End loop
i=1
n=组中的复选框数
而我
环
对于“组X”中的复选框i,将链接单元格分配给单元格(范围A1-->Z1)
端环
显然这不是VBA,但我不熟悉语法,有人知道吗
a) 如果可能执行此功能(即通过分组元素+分配链接单元格)
b) 我需要查找来编写它的命令/语法
非常感谢这是你想要的吗 下面的代码检查sheet1上的每个复选框,并设置从单元格A1开始的链接单元格属性,以此类推 让我们保持简单
Sub sample()
Dim i As Integer
Dim chk As Variant
i = 1
With Sheets("Sheet1")
For Each chk In .OLEObjects
If TypeName(chk.Object) = "CheckBox" Then
chk.LinkedCell = .Range("A" & i).Address
i = i + 1
End If
Next
End With
End Sub
此代码将执行您想要的操作:
Sub linkFromGroup()
Dim g ' we put groups in this variable
Dim gc As Integer ' group count - number of elements in group
Dim r As Range ' points to cell we will link to
Set r = Range("A1") ' initially point to cell A1 - this could be anything
' we will know something is a group when we can count the objects in the group
' if we try to count objects that don't exist we will get an error.
' we will trap that with the following line:
On Error Resume Next
' turn off screen updating while macro runs - or it will flicker
Application.ScreenUpdating = False
' loop over all the "shapes" in sheet1. A group is a special kind of shape
For Each g In Sheets("Sheet1").Shapes
' set count to zero
gc = 0
' see if we get a value other than zero
gc = g.GroupItems.Count ' on error we go to the next line and gc will still be zero
If gc > 0 Then
For ii = 1 To gc
g.GroupItems.Item(ii).Select
Selection.LinkedCell = r.Address ' right now I am assuming only check boxes in groups...
Selection.Caption = "linked to " & r.Address ' not necessary - but shows which box was linked to what.
Set r = r.Offset(1, 0) ' next check box will be linked with the next cell down from r
Next ii
End If
Next g
Application.ScreenUpdating = True ' turn on normal operation again
End Sub
运行此操作后我的测试表的外观示例(有两个组和一个复选框):
单个复选框未被触动-组被触动。我从来没有点击过$A$8框,所以它的值不会显示为真或假
您需要打开VBA编辑器(Alt-F11),插入模块,然后粘贴到上述代码中。然后可以使用(Alt-F8)运行它,并从显示的列表中拾取宏。有很多其他方法可以做到这一点。从您的问题听起来,您可以从这里修改代码确保首先在电子表格的副本上执行此操作-直到您确定此操作按您希望的方式运行非常感谢您抽出时间写出如此深思熟虑的答案!一个带屏幕帽的,非常有用的,谢谢,注意到你的警告:先复印一份。欢迎!请注意,另一个答案中有一些片段(例如,如何确定对象是否为复选框)也会对您有所帮助。每次我来到这里,我都会学到一些新的东西。你是我“今天的新事物”。所以谢谢你。你的回答对我也很有帮助-非常感谢你花时间回答并帮助我学习:)