0

在电子表格中,我有大量预先存在的复选框,手动设置每个链接的单元格将是一项繁琐的任务。

我希望将它们中的大量分组,然后编写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

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

非常感谢

4

2 回答 2

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

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

在此处输入图像描述

单个复选框没有被触及 - 组是。我从未点击过 $A$8 框,因此它的值不会显示为 TRUE 或 FALSE。

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

于 2013-05-14T00:53:58.183 回答
4

是你要找的吗?

下面的代码检查 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
于 2013-05-14T00:53:51.570 回答