Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter way to test range for a certain string

Tags:

excel

vba

Trying to create code that will export my Excel invoice sheet to PDF, to a specified file path. The path is based on the whether the invoice lists a certain product, ProductX.

This is what I came up with, but seems cumbersome to loop through every single cell in a range to see if ProductX is there.

Is there an easier way to do this? Appreciate any help!

Sub ExportToPDF()
'
Dim file_path As String
Dim search_range As Range
Dim each_cell As Range

' Set search_range as desired search range
Set search_range = ActiveSheet.Range("A53:R56")

For Each each_cell In search_range.Cells
    If InStr(1, each_cell.Value, "ProductX", vbTextCompare) Then
        file_path = Some_path_A
    Else: file_path = Some_path_B
    End If
Next each_cell

'Export the sheet as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, FileName:=file_path, Quality:=xlQualityStandard _
        , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True
End Sub
like image 597
cy6581 Avatar asked Dec 05 '22 15:12

cy6581


1 Answers

You can use Find for a partial match.

This code assumes that the returned path contains the filepath variable you need - you may need to tweak this.

Dim rng1 As Range
Set rng1 = ActiveSheet.Range("A53:R56").Find("ProductX", , xlFormulas, xlPart)
If rng1 Is Nothing Then Exit Sub

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=rng1.Value, Quality:=xlQualityStandard _
        , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
        True
like image 163
brettdj Avatar answered Dec 20 '22 00:12

brettdj