【问题标题】:Create another file but don't split worksheets into separate files创建另一个文件但不要将工作表拆分为单独的文件
【发布时间】:2023-02-03 03:29:51
【问题描述】:

将工作表分成单独的文件

嗨,我正在使用代码

Sub Split_Sheet_into_ExcelFiles()
    Dim FilePath As String
    FilePath = Application.ActiveWorkbook.Path
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    For Each Sheet In ThisWorkbook.Sheets
    Sheet.Copy
    Application.ActiveWorkbook.SaveAs Filename:=FilePath & "\" & Sheet.Name & ".xlsx"
    Application.ActiveWorkbook.Close False
    Next
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

它创建相同的文件,但我试图将多个工作表拆分为单独的文件。知道我打错了什么吗?谢谢

【问题讨论】:

  • 你调试过你的代码吗?我唯一看到的是,当您遍历 ThisWorkbook 的工作表时,您正在使用 ActiveWorkbook 读取路径。如果 ThisWorkbook 不是例程开始时的活动工作簿,您可能会得到意外的路径。

标签: excel vba


【解决方案1】:

将每个工作表导出到单个文件

Option Explicit

Sub ExportSheets()
    
    Const PROC_TITLE As String = "Export Sheets"
    
    Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
    
    Dim dFilePath As String: dFilePath = swb.Path
    
    If Len(dFilePath) = 0 Then
        MsgBox "The path cannot be determined." & vbLf & "Please save the " _
            & "workbook before using this procedure.", vbCritical, PROC_TITLE
        Exit Sub
    End If
    
    Application.ScreenUpdating = False
    
    Dim dwb As Workbook, ssh As Object, sshCount As Long
    
    For Each ssh In swb.Sheets
        If ssh.Visible = xlSheetVisible Then ' sheet is visible
            ssh.Copy
            Set dwb = Workbooks(Workbooks.Count)
            Application.DisplayAlerts = False ' overwrite without confirmation
                dwb.SaveAs Filename:=dFilePath & "" & ssh.Name
            Application.DisplayAlerts = False
            dwb.Close SaveChanges:=False
            sshCount = sshCount + 1
        'Else ' sheet is not visible; do nothing!?
        End If
    Next ssh

    Application.ScreenUpdating = True
    
    MsgBox sshCount & " sheet" & IIf(sshCount = 1, "", "s") _
        & " exported to individual files.", vbInformation, PROC_TITLE

End Sub

【讨论】:

    猜你喜欢
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    • 2016-02-07
    相关资源
    最近更新 更多