2013-05-13 129 views
0

在電子表格中,我有大量預先存在的複選框,手動設置每個鏈接單元格將是一項繁瑣的任務。使用VBA系統地爲一組複選框定義鏈接單元格(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,但我不熟悉的語法,沒有人知道 一)如果有可能執行這樣的功能(即通過分組元素+分配鏈接的單元格)b)我需要查找的命令/語法來編寫它。

非常感謝

回答

6

該代碼會做你想要什麼:

enter image description here:什麼我的測試表如下運行此之後(有兩個組,一個複選框)

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)運行它並從顯示的列表中選取宏。還有很多其他的方法可以做到這一點。聽起來你的問題是你可以調整這裏的代碼。 請確保您首先在電子表格的副本上執行此操作 - 直到您確定此操作符合您的要求!

+0

非常感謝您花時間寫出如此深思熟慮的答案!一個與屏幕上蓋,以及非常有用的,謝謝你,已經注意到你的警告:第一個副本。 – Gideon 2013-05-14 01:23:55

+0

不客氣!請注意,在其他答案中有一些片段(例如,如何確定某個對象是否爲複選框),這對您也會有所幫助。 – Floris 2013-05-14 01:57:22

3

這是你在找什麼?

下面的代碼檢查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 
+0

像TypeName的檢查!得到一個投票只是爲了... – Floris 2013-05-14 01:58:01

+0

謝謝:) @Floris – Santosh 2013-05-14 02:24:57

+1

每次我來到這裏,我學到了新的東西。你是我今天的「新事物」。所以謝謝。 – Floris 2013-05-14 02:28:01

相關問題