在 Excel VBS 中使用名称 Rang 在某些情况下不起作用

问题描述 投票:0回答:1

我正在尝试使用命名范围来控制单元格格式,但它似乎没有按预期工作:

不使用命名范围的 Sub 工作正常:

Sub COLOR_PATCH()
'
' This changes the interior color of a block of cells to whatever hex value the current active cell contains
'
Dim XX As String 'XX IS THE HEX VALUE of an RGB color
If ActiveCell.Value <> "" Then
    XX = ActiveCell.Value
    Range("$L$8:$R$31").Interior.Pattern = xlSolid
    Range("$L$8:$R$31").Interior.PatternColorIndex = xlAutomatic
    Range("$L$8:$R$31").Value = XX
    Range("$L$8:$R$31").Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
    Range("$L$8:$R$31").Interior.Color = HexToRGB(XX) 'HexToRGB is a function to convert HEX to RGB
    Range("$L$8:$R$31").Interior.TintAndShade = 0
    Range("$L$8:$R$31").Interior.PatternTintAndShade = 0
End If
End Sub

当我创建命名范围时,我得到了一个 运行时错误“1004” 对象“_Global”的方法“Range”失败

Sub COLOR_PATCH()
Dim CBLOCK As Range
Dim XX As String
Set CBLOCK = Range("$L$8:$R$31")
If ActiveCell.Value <> "" Then
    XX = ActiveCell.Value
    Range(CBLOCK).Interior.Pattern = xlSolid
    Range(CBLOCK).Interior.PatternColorIndex = xlAutomatic
    Range(CBLOCK).Value = XX
    Range(CBLOCK).Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
    Range(CBLOCK).Interior.Color = HexToRGB(XX)
    Range(CBLOCK).Interior.TintAndShade = 0
    Range(CBLOCK).Interior.PatternTintAndShade = 0
End If

结束子

excel vba named-ranges
1个回答
0
投票
  • CBLOCK
    是一个 Range 对象。代码应该是
CBLOCK.Interior.Pattern = xlSolid
Sub COLOR_PATCH()
Dim CBLOCK As Range
Dim XX As String
Set CBLOCK = Range("$L$8:$R$31")
If ActiveCell.Value <> "" Then
    XX = ActiveCell.Value
    With CBLOCK
        .Interior.Pattern = xlSolid
        .Interior.PatternColorIndex = xlAutomatic
        .Value = XX
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
        .Interior.Color = HexToRGB(XX)
        .Interior.TintAndShade = 0
        .Interior.PatternTintAndShade = 0
    End With
End If
© www.soinside.com 2019 - 2024. All rights reserved.