更短的方式来testing某个string的范围

尝试创build将我的Excel发票工作表导出到PDF的代码到指定的文件path。 该path基于发票是否列出某个产品ProductX。

这是我想出来的,但是在一个范围内的每个单元格中循环看看ProductX是否在那里似乎很麻烦。

有没有更简单的方法来做到这一点? 感谢任何帮助!

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 

您可以使用Find进行部分匹配。

这段代码假定返回的path包含你需要的文件pathvariables – 你可能需要调整它。

 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 

根据brettdj的build议,您可以使用下面提出的代码…

 Sub ExportToPDF() Dim file_path As String Dim search_range As String Dim each_cell As Range Dim rng1 As Range ' Set search_range as desired search range search_range = ActiveSheet.Range("A53:R56") Set rng1 = ActiveSheet.Range("A53:R56").Find("ProductX", , xlFormulas, xlPart) If Not rng1 Is Nothing Then file_path = Some_path_A Else file_path = Some_path_B End If 'Export the sheet as PDF ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=file_path, Quality:=xlQualityStandard _ , IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _ True End Sub 

我认为最简单的方法如下:

 If WorksheetFunction.CountIf(ActiveSheet.Range("A53:R56"), "*ProductX*") = 0 Then Exit Sub 

这可以进一步缩小为:

 If WorksheetFunction.CountIf(Range("A53:R56"), "*ProductX*") = 0 Then Exit Sub 

因为ActiveSheet默认的 ragnge worksheet资格

有一种方法可以用一行代码来精确地find它,但是只有当您在1列上进行search时,它才会起作用。 对于你的情况,我认为这将工作,因为通常产品名称将在一列。 代码如下:

 Dim test As Variant Product = "ProductX" ' Set search_range as desired search range search_range = Application.WorksheetFunction.Transpose(Sheets(1).Range("A53:A56")) If UBound(Filter(search_range, Product)) > -1 Then file_path = Some_path_A Else file_path = Some_path_B End If 

你可以尝试一下,让我知道这是否适合你。 如果没有,我会尝试find一种方法来做到多列,并改善答案