簡體   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