繁体   English   中英

使用单元格中的值作为宏中的范围

[英]Use value in cell as range in macro

我想使用单元格中的值作为动态方式来更改宏中的范围,更具体地说是在更改单元格的颜色时。

让我们说 CELL A1 托管所需的范围数据。 宏将始终查看此单元格。 A1 = 'B4' 中的文本因此我希望这是选定的单元格以进行颜色填充。 这将重复很多次并且数据会改变,这就是为什么我需要它是一个动态宏而不是条件格式。

以下是标准颜色宏,据我所知,VBA noob 抱歉。

Sub Colour2()
'
' Colour2 Macro
'

'
    Range("B4").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 16731903
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Sub

希望这是有道理的,并感谢您的理解和帮助。

单元格中提供的突出显示范围

  • 这是一个自动化的解决方案。 你什么都不跑。 只需复制相应模块中的代码即可。
  • 当您更改单元格A1中的范围地址时,颜色将应用于提供的范围地址的单元格并选择范围。

工作表 object 模块,例如Sheet1 (名称不在VBE Project Explorer中的括号中)

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    
    Const mAddress As String = "A1"
    Const ColorValue As Long = 16731903
    
    Dim mCell As Range: Set mCell = Range(mAddress)
    If Not Intersect(mCell, Target) Is Nothing Then
        On Error Resume Next
        Dim rg As Range: Set rg = Range(mCell.Value)
        On Error GoTo 0
        If Not rg Is Nothing Then
            Application.ScreenUpdating = False
            ' Removes the colors from all cells before applying the color.
            applyColor rg, ColorValue, True
            ' Applies the color without removing the previously applied colors.
            'applyColor rg, ColorValue
            rg.Select
            Application.ScreenUpdating = True
        End If
    End If

End Sub

标准模块,例如 Module1(可选在同一张表中 object 模块)

Sub applyColor( _
        ByVal rg As Range, _
        ByVal ColorValue As Long, _
        Optional ByVal resetBeforeApply As Boolean = False)
    If resetBeforeApply Then
        rg.Worksheet.Cells.Interior.Color = xlNone
    End If
    With rg.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = ColorValue
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Sub
  • 首选标准模块,因为它可以很容易地用于其他工作表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM