• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

How to improve code for finding a string in a worksheet

ThrottleWorks

Excel Ninja
Hi,

Whenever I open a file through macro for processing, I do below mentioned check in the file.

I find if the required column headers are present in the file. If headers are present macro resumes work else macro will get close.

I need your help in improving below mentioned code. Can anyone please suggest me how to better this code.

Dear moderator, I hope such kind of posts are allowed, my apologies if these are not allowed.

Please note - This is not urgent.

Code:
On Error Resume Next
        TempSht.Range("B1").Select
        Cells.Find(What:="SampleString", After:=ActiveCell, LookIn:=xlFormulas, SearchDirection:=xlPrevious).Activate
    On Error GoTo 0
    If ActiveCell.Value <> "SampleString" Then
        MsgBox "It seems 'SampleString' header is not present in .csv file, kindly re-check.", vbCritical
        End
    End If
    Col = ActiveCell.Column
 
Hi @Deepak Sir, thanks a lot for the help. I perform this check both on Excel file as well as CSV file.

This particular code I was using in a CSV file.

Sir, does finding string in .csv or .xls file require change in code, I am not aware. Please guide if possible.
 
I have asked as there are sevral methods to read from txt file.

Check this for xl

Code:
Sub find_h()
Dim hdr As String, sep As String: sep = ","
Dim toFind As String: toFind = "SampleString"

hdr = Join(Application.Transpose(Application.Transpose(ActiveSheet.Range("A1").CurrentRegion.Resize(1))), sep)
hdr = Replace(Replace(hdr, sep & sep, sep), sep & sep, sep)

If Not InStr(hdr, toFind) > 0 Then MsgBox "It seems '" & toFind & "' header is not present in file, kindly re-check.", vbCritical

End Sub
 
Back
Top