如何将工作表A保存到文件夹A,将工作表B保存到文件夹B?

时间:2015-12-23 05:17:26

标签: excel vba excel-vba save

如何在VBA Excel中将Sheet1保存到文件夹A和Sheet2到文件夹B? 在我的工作簿中,我有4个工作表C后端,工作表D是界面。

文件夹路径为:

  • C:\Main Folder\Folder A\
  • C:\Main Folder\Folder B\

    FilePath1 = "C:\Main Folder\Folder A\"
    FilePath2 = "C:\Main Folder\Folder B\"
    
    Sheets("Sheet1").Copy
    Filename = ControlNumber.Value
    ActiveWorkbook.SaveCopyAs FilePath1 & "\" & Filename & ".xls"
    ActiveWorkbook.Close savechanges:=False
    
    Sheets("Sheet2").Copy
    Filename = ControlNumber.Value
    ActiveWorkbook.SaveCopyAs FilePath2 & "\" & Filename & ".xls"
    

2 个答案:

答案 0 :(得分:0)

您的代码以这种方式正常运行

ALooper_pollAll()

你得到了什么错误?

用于测试我设置:

FilePath1 = "C:\Main Folder\Folder A\"
FilePath2 = "C:\Main Folder\Folder B\"

Sheets("Sheet1").Copy
Filename = ControlNumber.Value
ActiveWorkbook.SaveAs FilePath1 & Filename & ".xls"
ActiveWorkbook.Close savechanges:=False

Sheets("Sheet2").Copy
Filename = ControlNumber.Value
ActiveWorkbook.SaveCopyAs FilePath2 & Filename & ".xls"
ActiveWorkbook.Close savechanges:=False

修改

Dim ControlNumber As Range
Set ControlNumber = Sheet1.Cells(1, 1)
Dim FilePath1 As String, FilePath2 As String, Filename As String

答案 1 :(得分:0)

您已在路径分隔符中包含两次,即在文件路径中以及保存文件时。从文件名中删除“/”或保存时

On Error Resume Next
MkDir Environ("USERPROFILE") & "\Main Folder"
MkDir Environ("USERPROFILE") & "\Main Folder\Folder A\"
MkDir Environ("USERPROFILE") & "\Main Folder\Folder B\"
On Error GoTo 0

FilePath1 = Environ("USERPROFILE") & "\Main Folder\Folder A\"
FilePath2 = Environ("USERPROFILE") & "\Main Folder\Folder B\"

Sheets("Sheet1").Copy
Filename = ControlNumber.Value
ActiveWorkbook.SaveAs FilePath1 & Filename & ".xls"
ActiveWorkbook.Close savechanges:=False

Sheets("Sheet2").Copy
Filename = ControlNumber.Value
ActiveWorkbook.SaveCopyAs FilePath2 & Filename & ".xls"
ActiveWorkbook.Close savechanges:=False