- For Each
- For Next
- Do...Loop
Qué fila ocupa cada celda
Deseamos escribir la Fila que corresponde a cada celda dentro de un rango. Los rangos elegidos son- Primer rango A1.A10 resuelto con For Each
- Segundo rango B1.B10 resuelto con For Next
- Tercer rango C1.C10 resuelto con Do...Loop
Las tres macros siguientes permiten obtener cada uno de los rangos indicados.
Sub Filas1() 'Usando For Each Dim Rango As Range Dim Celda As Range Set Rango = Range("A1:A10") For Each Celda In Rango Celda.Value = "Fila " & Celda.Row Next End Sub Sub Filas2() 'Usando For Each Dim Rango As Range Dim Celda As Range Dim n As Integer 'nº de filas Dim i As Integer Set Rango = Range("B1:B10") n = Rango.Rows.Count For i = 1 To n Set Celda = Rango.Cells(i, 1) Celda = "Fila " & Celda.Row Next End Sub Sub Filas3() 'Usando Do...Loop Dim Rango As Range Dim Celda As Range Dim n As Integer 'nº filas Dim i As Integer Set Rango = Range("C1:C10") n = Rango.Rows.Count Do i = i + 1 If i > n Then Exit Do Set Celda = Rango.Cells(i, 1) Celda = "Fila " & Celda.Row Loop End Sub
Rango rectangular
Podemos ejecutar otra macro que rellena el rango E3:H10. Se trata de un rango rectangular que no comienza ni el la fila 1, ni en la columna 1.Resuelto con el bucle ForEach.
Sub FilasColumnas() Dim Rango As Range Dim Celda As Range Set Rango = Range("E3:H10") For Each Celda In Rango Celda = "F" & Celda.Row & "~" & "C" & Celda.Column Next End Sub
No hay comentarios:
Publicar un comentario