我想根据行号更改单元格样式。我还是 VBA 的新手。
这是我的代码:
Sub format()
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To FinalRow
If Rows.Count = 2 * i + 1 Then
Selection.Style = "Good"
ElseIf Rows.Count = 2 * i Then
Selection.Style = "Bad"
End If
ActiveCell.Offset(1, 0).Select
Next i
End Sub
循环移动到下一个单元格,但如果满足条件则不会突出显示。请你帮帮我。
最佳答案
我建议如下:
Option Explicit
Public Sub FormatEvenOddRowNumbers()
Dim FinalRow As Long
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
Dim i As Long
For i = 1 To FinalRow
If i Mod 2 = 0 Then 'even row number
Cells(i, 1).Style = "Good"
Else 'odd row number
Cells(i, 1).Style = "Bad"
End If
Next i
End Sub
要测试行号是否为“偶数”,您可以使用
If i Mod 2 = 0 Then
你也不需要测试“奇数”,因为如果它不是“偶数”,它必须是“奇数”,所以你可以使用 Else
没有任何标准。尽量避免使用
.Select
它使您的代码变慢。见 How to avoid using Select in Excel VBA .而是直接访问单元格,如 Cells(row, column)
.
关于vba - 根据VBA中的行号突出显示单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51891734/