简体   繁体   中英

Excel VBA, How to use the selection in a dropdown list on one sheet format(color) a range of cells on another sheet

From what I've gathered, conditional formatting can't be done across sheets in a workbook so what I'm trying to do now is use VBA.

I would like a word (let's say "yes" or "no") selected in a dropdown list on sheet1! to then color a range of cells; Range("J3:P29") on sheet3!. If "yes" is selected the range will be colored and if "no" is selected then the range will not be colored.

I used the macrorecorder to record the code below. However, it doesn't record the selection from the dropdown list. It just replaced the action with commas.

Sub RangeRed()
'
' RangeRed Macro
'

'
    Range("J3:P29").Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 255
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With

End Sub

I would greatly appreciate some help. Thanks!

Couple changes you need to make.

  1. You'll need to leverage the Worksheet_Change event on your sheet1 to update your sheet3.
  2. In your code, you'll need to refer to sheet3 directly because you won't be able to select it from the sheet1 worksheet event.
  3. Using the Target Value, evaluate whether or not it meets your specified condition and update sheet3 as desired

Open the VB editor and open the Sheet1 code. Then paste the following code.

Private Sub Worksheet_Change(ByVal Target As Range)
' Target.Value will be contain the value of the changed cell
If Target.Value = "Yes" Then 
    With ThisWorkbook.Sheets("Sheet3").Range("J3:J5").Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 255 
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
Else
    With ThisWorkbook.Sheets("Sheet3").Range("J3:J5").Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 0 ' change to whatever color you want if Yes is not selected
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End If

End Sub

Note that Target will capture any range of cells that is changed on the sheet. to counter that, you can name the cell that has your dropdown, and then in the Worksheet_Change event, only evaluate Target if the name of the range is matched; for example

If Target.Name = "MyDropDown" Then
     ' Evaluate the value of Target and update sheet3 as intended

End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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