VBA/Excel/Access/Word/Excel/Range Loop
Содержание
For Each Loops for a range
<source lang="vb">
Sub forEach()
Dim c As Range For Each c In Range("A1:E10") c.Value = c.Row * c.Column Next
End Sub
</source>
Get rows from a named range (name the range before running this cript)
<source lang="vb">
Sub Bold()
Dim rngRow As Range For Each rngRow In Range("yourRange").Rows If rngRow.Cells(1).Value > 1 Then rngRow.Font.Bold = True Else rngRow.Font.Bold = False End If Next rngRow
End Sub
</source>
Get Rows from a range
<source lang="vb">
Sub Bold()
Dim rngRow As Range For Each rngRow In Range("A1:E5").Rows If rngRow.Cells(1).Value > 1 Then rngRow.Font.Bold = True Else rngRow.Font.Bold = False End If Next rngRow
End Sub
</source>
Loop through all cells in a range
<source lang="vb">
Sub ResetTest1()
For Each n In Range("A1:A13") " Substitute your range here If n.Value <> 0 Then n.Value = 0 End If Next n
End Sub
</source>
Loop through a range cell by cell
<source lang="vb">
Sub ColorCells1()
Dim myRange As Range Dim i As Long, j As Long Set myRange = Range("A1:A5") For i = 1 To myRange.Rows.Count For j = 1 To myRange.Columns.Count If myRange.Cells(i, j).Value < 100 Then myRange.Cells(i, j).Font.ColorIndex = 3 Else myRange.Cells(i, j).Font.ColorIndex = 1 End If Next j Next i
End Sub
</source>
Set the value in a range by cell index
<source lang="vb">
Sub ColorCells2()
Dim myRange As Range Dim i As Long, j As Long Set myRange = Range("A1:E5") For i = 1 To myRange.Rows.Count For j = 1 To myRange.Columns.Count If myRange(i, j).Value < 10 Then myRange(i, j).Font.ColorIndex = 5 Else myRange(i, j).Font.ColorIndex = 1 End If Next j Next i
End Sub
</source>