Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA If cell.Value =... then

Tags:

excel

vba

I have this code which works well:

Sub colortest()
Dim cell As Range
For Each cell In Range("Range1")
If cell.Value = "Word1" Then
cell.Interior.Color = XlRgbColor.rgbLightGreen
ElseIf cell.Value = "Word2" Then
cell.Interior.Color = XlRgbColor.rgbOrange
ElseIf cell.Value = "Word3" Then
cell.Interior.Color = XlRgbColor.rgbRed
End If
Next cell
End Sub

My problem is the values work only if the cell contains only that text. But my cells are usually like this: "Something, 10254, 15/15, Word1 Another Word" I only need the Word1. Thank you,

like image 472
Kerem Ozan Bayraktar Avatar asked Mar 12 '15 09:03

Kerem Ozan Bayraktar


People also ask

How do you check if cell has value in Excel VBA?

With a Worksheet Cell If you wish to test whether a worksheet cell is empty in VBA, you can not use the worksheet function called ISBLANK. In VBA, you must use the ISEMPTY function. In this example, we will test whether cell A1 is empty. If cell A1 is empty, the message "Cell A1 is empty" will be displayed.

How do you use multiple conditions in if statement Excel VBA?

You can use the OR operator with the VBA IF statement to test multiple conditions. When you use it, it allows you to test two or more conditions simultaneously and returns true if any of those conditions are true. But if all the conditions are false only then it returns false in the result.

Can you write an if statement in VBA?

Use the If...Then... Else statement to run a specific statement or a block of statements, depending on the value of a condition. If...Then... Else statements can be nested to as many levels as you need.


1 Answers

You can determine if as certain word is found in a cell by using

If InStr(cell.Value, "Word1") > 0 Then

If Word1 is found in the string the InStr() function will return the location of the first character of Word1 in the string.

like image 57
Netloh Avatar answered Sep 21 '22 18:09

Netloh