如何将名为“X,Y或Z …”的工作表保存到子文件夹? 多variablesstring?

这是一个VBA代码,如果工作表中有一个名为“Orange,Apple …”的工作表,那么将Excel工作簿保存在工作簿目录下的“食品”文件夹中。现在只有在代码中放入一种食品时才能使用。 IE中:

sName = "Orange" 

以下是完整的代码:

 Sub CheckWorksheetNames() Dim sName As String Dim sFound As Boolean Dim strPath As String strPath = ThisWorkbook.Path & "\Folder\Food\" & ActiveWorkbook.Name sName = "Orange" Or "Apple" Or "Broccoli" Or "Cheese" If sName = "" Then Exit Sub sFound = False On Error Resume Next ActiveWorkbook.Sheets(sName).Select If Err = 0 Then sFound = True On Error GoTo 0 If sFound = True Then ActiveWorkbook.SaveAs Filename:=strPath End If End Sub 

我如何得到它通过多个variables? 也就是说,如果工作簿中有名为“Orange,Apple,Broccoli …”的工作表,

您可以循环查看所有工作表,并检查它们是否匹配:

 For Each s in Sheets If s.Name = "Orange" Or s.Name = "Apple" Or s.Name = "Broccoli" Or s.Name = "Cheese" Then ActiveWorkbook.SaveAs strPath Exit For End If Next 

要么

 For Each s in Sheets Select Case s.Name Case "Orange", "Apple", "Broccoli", "Cheese" ActiveWorkbook.SaveAs strPath Exit For End Select Next 
 Sub CheckWorksheetNames() Dim sName, arrNames '<<EDIT: removed "As String" from sName Dim sFound As Boolean Dim strPath As String strPath = ThisWorkbook.Path & "\Folder\Food\" & ActiveWorkbook.Name arrNames = Array("Orange","Apple","Broccoli","Cheese") For Each sName in arrNames If SheetExists(sName, ActiveWorkbook) Then strPath = ThisWorkbook.Path & "\Folder\" & sName & "\" & _ ActiveWorkbook.Name ActiveWorkbook.SaveAs Filename:=strPath End If Next End Sub Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean Dim sht As Worksheet If wb Is Nothing Then Set wb = ThisWorkbook On Error Resume Next Set sht = wb.Sheets(shtName) On Error GoTo 0 SheetExists = Not sht Is Nothing End Function