Search code examples
excelvba

Using variables VBA


I have a simple code to check correct answers in an excel sheet:

   If ThisWorkbook.Sheets("test1").Range("B13") = "X" Or ThisWorkbook.Sheets("test1").Range("B13") = "x" Then
ThisWorkbook.Sheets("test1").Range("A9") = "CORRECT"
ThisWorkbook.Sheets("test1").Range("A9").Interior.Color = RGB(0, 176, 80)

Else
ThisWorkbook.Sheets("test1").Range("A9") = "INCORRECT"
ThisWorkbook.Sheets("test1").Range("A9").Interior.Color = RGB(255, 0, 0)
End If

I need to find a way to make "B13" a variable, same for "A9" Problem is the variable needs to hold value ("incorrect") but also needs to change color of the cell, so if I declare the variable as "string", I cannot change the color of the cell.

They show up again later after a few conditions:

ThisWorkbook.Sheets("test1").Range("B13") = "X"
ThisWorkbook.Sheets("test1").Range("B13").Font.Bold = True
ThisWorkbook.Sheets("test1").Range("B13").Font.Color = vbGreen
ThisWorkbook.Sheets("test1").Range("C13").Font.Bold = True
ThisWorkbook.Sheets("test1").Range("C13").Font.Color = vbGreen

so, the variable also needs to allow me to change the font.

I tried:

Dim i as string
Dim i as range

...but I always get an error.

sometihng like:

Dim i as String
i = ThisWorkbook.Sheets("test1").Range("B13")

i.value = "correct"
i.Interior.Color = RGB(0, 176, 80)
i.Font.Bold = True
i.Font.Color = vbGreen

Solution

  • Setting rng as range and using set as Black Cat suggested worked