Domanda

Questa è una di quelle cose che sono sicuro che ci sia una funzione built-in per la (e posso ben è stato detto in passato), ma sto graffiare la mia testa per ricordarlo.

Come faccio a ciclo attraverso ogni fila di una gamma più colonne utilizzando Excel VBA? Tutti i tutorial che ho cercato fino sembrano solo parlare di lavoro attraverso una serie unidimensionale ...

È stato utile?

Soluzione

Dim a As Range, b As Range

Set a = Selection

For Each b In a.Rows
    MsgBox b.Address
Next

Altri suggerimenti

Qualcosa di simile a questo:

Dim rng As Range
Dim row As Range
Dim cell As Range

Set rng = Range("A1:C2")

For Each row In rng.Rows
  For Each cell in row.Cells
    'Do Something
  Next cell
Next row

Proprio imbattuto in questo e ho pensato di suggerire la mia soluzione. Io di solito piace usare il costruito nel funzionalità di assegnazione di un intervallo per un array multi-dim (credo che sia anche il JS programmatore in me).

Mi capita spesso di scrivere il codice in questo modo:

Sub arrayBuilder()

myarray = Range("A1:D4")

'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned

For i = 1 To UBound(myarray)

    For j = 1 To UBound(myarray, 2)

    Debug.Print (myarray(i, j))

    Next j

Next i

End Sub

L'assegnazione gamme alle variabili è un modo molto potente per manipolare i dati in VBA.

In Loops, preferisco sempre usare la classe Cells, utilizzando il metodo di riferimento R1C1, in questo modo:

Cells(rr, col).Formula = ...

Questo mi permette a rapidamente e facilmente ciclo per un Gamma di cellule facilmente:

Dim r As Long
Dim c As Long

c = GetTargetColumn() ' Or you could just set this manually, like: c = 1

With Sheet1 ' <-- You should always qualify a range with a sheet!

    For r = 1 To 10 ' Or 1 To (Ubound(MyListOfStuff) + 1)

        ' Here we're looping over all the cells in rows 1 to 10, in Column "c"
        .Cells(r, c).Value = MyListOfStuff(r)

        '---- or ----

        '...to easily copy from one place to another (even with an offset of rows and columns)
        .Cells(r, c).Value = Sheet2.Cells(r + 3, 17).Value


    Next r

End With
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top