Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA, if a string contains a certain letter

Tags:

excel

vba

I do not usually work with VBA and I cannot figure this out. I am trying to determine whether a certain letter is contained within a string on my spreadhseet.

Private Sub CommandButton1_Click()
Dim myString As String
RowCount = WorksheetFunction.CountA(Range("A:A"))
MsgBox RowCount
For i = 2 To RowCount
    myString = Trim(Cells(i, 1).Value)
    If myString.Contains("A") Then
        oldStr = Cells(i, 15).Value
        newStr = Left(oldStr, oldStr.IndexOf("A"))
    End If
Next          
End Sub

This code should go through a list of values and if it encounters the letter A to remove it and everything that comes after it. I am getting problems at my IF statement, Invalid Qualifier. How would I be able to make my IF statement output whether or not the String in the cell contains the letter A?

Thank you very much

like image 401
JahKnows Avatar asked Jul 07 '14 18:07

JahKnows


People also ask

How do you check if a string contains a character in VBA?

The VBA InStr function is one of the most useful string manipulation functions around. You can use it to test if a string, cell or range contains the substring you want to find. If it does, “InStr” will return the position in the text string where your substring begins.

How do you check if a string is AlphaNumeric in VBA?

Press Alt + F11 and create a new module. The AlphaNumeric function will return TRUE if all of the values in the string are alphanumeric. Otherwise, it will return FALSE.

How do I find a specific word in Excel VBA?

This functionality is equivalent to using the 'Find All' option you can choose when you use the normal find functionality available by pressing CTRL + F . Be sure to set strToFind to your desired string, and change Sheet1 to match the name of whichever sheet you want to search over.

What does CHR () do in VBA?

The Microsoft Excel CHR function returns the character based on the ASCII value. The CHR function is a built-in function in Excel that is categorized as a String/Text Function. It can be used as a VBA function (VBA) in Excel.


1 Answers

Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.

If InStr(myString, "A") > 0 Then

InStr MSDN Website

For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.

Left(oldStr, InStr(oldStr, "A"))
like image 154
Mark Balhoff Avatar answered Sep 19 '22 14:09

Mark Balhoff