VBA  X- Range Selection and Manipulation

 

We can program a VBA that can select certain range of cells and at the same time  perform certain tasks according to a set of conditions. In this example, I program the VBA such that it can accept range input from the user and then change the mark to blue if it is more than or equal to 50 and change it to red if the mark is less than 50.

 

Private Sub CommandButton1_Click()
Dim rng, cell As Range, selectedRng As String
selectedRng = InputBox("Enter your range")
Set rng = Range(selectedRng)
For Each cell In rng
If cell.Value >= 50 Then
cell.Font.ColorIndex = 5
Else
cell.Font.ColorIndex = 3
End If
Next cell
End Sub


Explanation:

The InputBox function is used to accept value from the users.

rng and cell are declared as a  Range variable using the Dim statement while selectedRng is declared as a string that receive input from the user.

Once the input is obtained from the user, it is stored using the Set method and the Range function.

For Each cell In rng ......Net cell is a loop that can iterate through the selected range, one cell at a time.

The If...Then...Else statements are to specify the color of the font according to the range of values determined by the conditions.

 

 

 

 

 

 

 

 

 

 

 [Back to VBToday]