使用VBA系统地为一组复选框定义链接的单元格(excel)

Gid*_*eon 0 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
Run Code Online (Sandbox Code Playgroud)

显然这不是VBA,但我不熟悉语法,有没有人知道a)是否可以执行这样的功能(即通过分组元素+分配链接的单元格)b)我需要查找的命令/语法写它.

非常感谢

Flo*_*ris 6

此代码将执行您想要的操作:

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
Run Code Online (Sandbox Code Playgroud)

运行此测试表之后我的测试表的示例(有两个组和一个复选框):

在此输入图像描述

单个复选框没有被触及 - 小组是.我从未点击过$ 8 $的盒子,所以它的值不会显示为TRUE或FALSE.

您需要打开VBA编辑器(Alt-F11),插入模块,然后粘贴上面的代码.然后,您可以使用(Alt-F8)运行它并从显示的列表中选择宏.还有很多其他方法可以做到这一点.从你的问题来看,你可以从这里调整代码.确保首先在电子表格的副本上执行此操作 - 直到您确定这是按照您的意愿运行!