问题
I am trying to alter the following code which copies sheet1 from the active workbook and saves it to a folder by with a function called CreateFolder, all works well.
From Here: Tweak code to copy sheet1 of a excel file to sheet1 new excel file
I have trying to alter it to copy the entire workbook to send to the the folder created by CreateFolder.
Thanks
Edit: Updated Code
Sub CopySheets()
Dim SourceWB As Workbook
Dim filePath As String
'Turns off screenupdating and events:
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'path refers to your LimeSurvey workbook
Set SourceWB = ActiveWorkbook
filePath = CreateFolder
SourceWB.SaveAs filePath
SourceWB.Close
Set SourceWB = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Function CreateFolder() As String
Dim fso As Object, MyFolder As String
Set fso = CreateObject("Scripting.FileSystemObject")
MyFolder = ThisWorkbook.Path & "\360 Compiled Repository"
If fso.FolderExists(MyFolder) = False Then
fso.CreateFolder (MyFolder)
End If
MyFolder = MyFolder & "\" & Format(Now(), "MMM_YYYY")
If fso.FolderExists(MyFolder) = False Then
fso.CreateFolder (MyFolder)
End If
CreateFolder = MyFolder & "\360 Compiled Repository" & " " & Range("CO3") & " " & Format(Now(), "DD-MM-YY hh.mm") & ".xls"
Set fso = Nothing
End Function
回答1:
To copy entire workbook you can use the below code
Sub CopySheets()
Dim SourceWB As Workbook
Dim filePath As String
'Turns off screenupdating and events:
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'path refers to your LimeSurvey workbook
Set SourceWB = Workbooks.Open(ThisWorkbook.Path & "\LimeSurvey.xls")
filePath = CreateFolder
SourceWB.SaveAs filePath
SourceWB.Close
Set SourceWB = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Function CreateFolder() As String
Dim fso As Object, MyFolder As String
Set fso = CreateObject("Scripting.FileSystemObject")
MyFolder = ThisWorkbook.path & "\Reports"
If fso.FolderExists(MyFolder) = False Then
fso.CreateFolder (MyFolder)
End If
MyFolder = MyFolder & "\" & Format(Now(), "MMM_YYYY")
If fso.FolderExists(MyFolder) = False Then
fso.CreateFolder (MyFolder)
End If
CreateFolder = MyFolder & "\Data " & Format(Now(), "DD-MM-YY hh.mm.ss") & ".xls"
Set fso = Nothing
End Function
来源:https://stackoverflow.com/questions/16386394/change-copy-sheet1-to-copy-workbook-in-macro