VBA保存在新目录中,具体取决于工作表名称

时间:2017-06-22 10:12:14

标签: vba

我正在尝试准备打开文件夹中所有文件的代码,检查打开文件中的工作表名称,并根据该工作表的名称将其重新保存到新文件夹中。但是,当我尝试添加IF语句来检查工作表名称是否存在时,它告诉我该方法不存在。有人能够建议更合适的方法吗?

Dim MyFile As String
MyPath = "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\"
MyFile = Dir(MyPath)
Do While MyFile <> ""
If MyFile Like "*.xlsx" Then
Workbooks.Open MyPath & MyFile

Dim ws1 As Worksheet
Set ws1 = Sheets("Adult_Return")

If ws1.Exists Then

ChDir "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\Return"
ActiveWorkbook.SaveAs Filename:=MyFile & ".xlsx"

Else

ChDir "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\Single"
ActiveWorkbook.SaveAs Filename:=MyFile & ".xlsx"

感谢。

1 个答案:

答案 0 :(得分:0)

创建一个函数:

Function SheetExists(wb As Workbook, sheetName As String)

    Dim ws As Worksheet
    SheetExists = False
    For Each ws In wb.Sheets
        If UCase(ws.Name) = UCase(sheetName) Then
            SheetExists = True
            Exit Function
        End If
    Next ws

End Function

这样称呼:

Dim wb As Workbook
Set wb = Workbooks.Open(MyPath & MyFile)
If SheetExists(wb, "Adult_Return") Then
...
顺便说一下:您不必执行chdir,只需将路径放入SaveAs:

wb.SaveAs "Q:\Folder Name1\Folder Name2\Folder Name3\Folder Name4\Single\" & MyFile & ".xlsx

并且:不要忘记关闭工作簿!