[英]Using VBA to systematically define the linked cell for a group of check boxes (excel)
在電子表格中,我有很多預先存在的復選框,手動設置每個復選框的鏈接單元將是一項繁瑣的任務。
我希望將它們分組,然后編寫實現以下目的的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)我需要查找的命令/語法寫。
非常感謝
此代碼將執行您想要的操作:
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)並從顯示的列表中選擇宏來運行它。 您還有許多其他方法可以執行此操作。 從您的問題聽起來,您可以從此處改編代碼。 確保首先在電子表格的副本上執行此操作-直到確定它可以按預期運行為止!
是您要找的東西嗎?
下面的代碼檢查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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.