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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With