简体   繁体   中英

Excel VBA Range Command Click Multiple Cells

I'm trying to understand the range function with a VB macro to make reporting easier at work. Plenty of help online about this but it only works for one cell. I want this solution to work for multiple cells stacked in a column.

I want to use a command button.

I'll simplify the scenario. If cell A1 = "1" then B2 should say "Green". If "2" then "Yellow" and if "3" then "Red".

Private Sub CommandButton1_Click()

Dim TrafficCode As Integer, TrafficSignal As String
TrafficCode = Range("A1").Value

If TrafficCode = 1 Then TrafficSignal = "Green" Else
If TrafficCode = 2 Then TrafficSignal = "Yellow" Else
If TrafficCode = 3 Then TrafficSignal = "Red"

Range("B1").Value = SA3

End Sub

This all works FINE for me for the one cell (A1).

But what if I want to do more than one cell? Let's say I've got cells A1:A5 with 1, 3, 2, 3, 2

How do I get them to display Green, Red, Yellow, Red, Yellow in B1:B5 ?

I obviously try to edit the Range("A1:A5") etc but I get an error.

The below doesn't work for me.

Private Sub CommandButton1_Click()

Dim TrafficCode As Integer, TrafficSignal As String
TrafficCode = Range("A1:A5").Value

If TrafficCode = 1 Then TrafficSignal = "Green" Else
If TrafficCode = 2 Then TrafficSignal = "Yellow" Else
If TrafficCode = 3 Then TrafficSignal = "Red"

Range("B1:B5").Value = SA3

End Sub

Clearly missing something. I think the logic I'm using is wrong.

Can anyone assist?

Have a look at this:

Sub Traffic_Light()

Dim myRange As String
Dim rCell As Range

myRange = "A1:A5"

For Each rCell In Range(myRange).Cells

Select Case rCell.Value

Case Is = 1
    rCell.Offset(0, 1) = "Green"
Case Is = 2
    rCell.Offset(0, 1) = "Amber"
Case Is = 3
    rCell.Offset(0, 1) = "Red"
Case Else

End Select

Next rCell

End Sub

It walks down the range, checks the value then puts some text in the column next to the value. It should be enough to get you started.

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