简体   繁体   中英

VBA How to loop through columns

This code adds a spinner button in each row. How could I write it to add a spinner button in each column... Lets say I want to add a spinner button in A1, B1, C1... G1.

Dim i As Integer
For i = 1 To 7
    ActiveSheet.Spinners.Add(Range("A" & i).Left, Range("A" & i).Top, 69.5, 20).Select
Next

If you loop over the elements of a range, it does not matterr if you traverse columns or rows. Here is a Button example:

Sub BoxAdder()
    Dim rng As Range, r As Range, bt As Button, s As Shape
    Set rng = Range("A1:G1")

    For Each r In rng
        ActiveSheet.Buttons.Add(94.5, 75.75, 51, 27.75).Select
        Set bt = Selection
        bt.Characters.Text = r.Address(0, 0)
        Set s = ActiveSheet.Shapes(Selection.Name)
        With s
            .Top = r.Top
            .Left = r.Left
            .Width = r.Width
            .Height = r.Height
        End With
    Next r
End Sub

The code places buttons on cells A1, B1, C1, D1, E1. F1, and G1 sequentially. To place the buttons down a column, just change:

Set rng = Range("A1:G1")

to:

Set rng = Range("A1:A4")

Note that for the purposes of moving and sizing, I treat each Button as a Shape .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM