Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations GregLocock on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search for string in excel cells

Status
Not open for further replies.

Strongpauly

Computer
Mar 19, 2004
3
I'm trying to write a macro that will delete a column in excel if the title has a certain sequence of letters. I can't seem to get the syntax right, or maybe im going about it in completely the wrong way as im an absolute novice when it comes to writing in VBA. So far i've got:

Sub Test_Deleting()
Dim Looking As Long
Dim TotalColumns As Long
Looking = 0
TotalColumns = Application.WorksheetFunction.CountA(Range("1:1"))
Do While Looking <> TotalColumns
Looking = Looking + 1
If Application.WorksheetFunction.IsError(Application.WorksheetFunction.Search("exp", Cells(1, Looking))) = False Then Selection.EntireColumn.Delete
Loop
End Sub

I wasn't sure if there was a VBA function to search the active cell for a certain string, so i tried to use the excel functions. I can get Excel to distinguish between those columns with the string in the title, and those without, but can't seem to get it to work in VBA.

Any help would be appreciated
Thanks SP
 
Replies continue below

Recommended for you

Hello,

I think this should work

Sub DELETE_EXP()
For MY_COLS = Range("IV1").End(xlToLeft).Column To 1 Step -1
CURRENT_CELL = Range("A1").Offset(0, MY_COLS - 1).Value
If CURRENT_CELL Like "exp" Or CURRENT_CELL Like "*exp" Or CURRENT_CELL Like "exp*" Or CURRENT_CELL Like "*exp*" Then
Columns(MY_COLS).Delete
End If
Next MY_COLS
End Sub

Is it OK?

----------------------------------
Hope this helps.
----------------------------------

maybe only a drafter
but the best user at this company!
 
Cheers! With a little fiddling it now seems to work, but is there anyway to make it not case sensitive, because i found that it would delete "exp", but not "Exp".

Thanks again.
 
Hello,

Can't think of a way immediately other than adding Or CURRENT_CELL Like "Exp" and all the other variants.



----------------------------------
Hope this helps.
----------------------------------

maybe only a drafter
but the best user at this company!
 

Improved procedure:

Sub DELETE_EXP()
For MY_COLS = Range("IV1").End(xlToLeft).Column To 1 Step -1
CURRENT_CELL = Lcase(Range("A1").Offset(0, MY_COLS - 1).Value)
If CURRENT_CELL Like "exp" Or _
CURRENT_CELL Like "*exp" Or _
CURRENT_CELL Like "exp*" Or _
CURRENT_CELL Like "*exp*" Then
Columns(MY_COLS).Delete
End If
Next MY_COLS
End Sub

by adding "Lcase()" to the procedure you will get all text in variable in Lover Case and you can compare it with with your strings. Text in cell is unchanged.




Vlado
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor