将选择范围扩展到 VBA 中的上下一行。

huangapple go评论126阅读模式
英文:

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
英文:

将选择范围扩展到 VBA 中的上下一行。

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
英文:

No need to Select.

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

huangapple
  • 本文由 发表于 2023年3月7日 02:57:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654772.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定