英文:
Extend the range of selection to a row above and below in vba
问题
[![在此输入图片描述][1]][1]
[1]: https://i.stack.imgur.com/SFLJk.png
我正在尝试选择A3右侧的单元格,并选择上下的行,然后在VBA中将背景设置为黑色,字体设置为白色。但我的代码将执行如上图所示的操作。
```vba
Sub header()
Range("A2:A4").Select
Range("A3").Activate
Range(Selection, Selection.End(xlToRight)).Select
Selection.Interior.ColorIndex = 1
Selection.Font.ColorIndex = 2
End Sub
英文:
I'm trying to select cells right of A3, and select the row above and below, and set the background to black and font to white in VBA. But my code will do something shown in the picture above.
Sub header()
Range("A2:A4").Select
Range("A3").Activate
Range(Selection, Selection.End(xlToRight)).Select
Selection.Interior.ColorIndex = 1
Selection.Font.ColorIndex = 2
End Sub
答案1
得分: 1
Dim ws As Worksheet
Set ws = ActiveSheet
With ws
Dim lastCol As Long
lastCol = .Cells(3, .Columns.Count).End(xlToLeft).Column
Dim rng As Range
Set rng = .Range("A2", .Cells(4, lastCol))
End With
rng.Interior.ColorIndex = 1
rng.Font.ColorIndex = 2
我建议使用.Color
而不是.ColorIndex
:
rng.Interior.Color = vbBlack
rng.Font.Color = vbWhite
英文:
Dim ws As Worksheet
Set ws = ActiveSheet
With ws
Dim lastCol As Long
lastCol = .Cells(3, .Columns.Count).End(xlToLeft).Column
Dim rng As Range
Set rng = .Range("A2", .Cells(4, lastCol))
End With
rng.Interior.ColorIndex = 1
rng.Font.ColorIndex = 2
I'd suggest using .Color
instead of .ColorIndex
:
rng.Interior.Color = vbBlack
rng.Font.Color = vbWhite
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论