ranjanagarwal
New Member
- Joined
- Jul 12, 2015
- Messages
- 13
I have a workbook "Test" with sheets "A", "B", "C" etc. I am looking to move each of these sheets and save them in the same location as workbook "Test" using a file name from a cell in the sheet.
I am trying to use the following code for the above that I found in one of the MrExcel threads: It only works to save the first sheet. After that it gives Script out of range error pointing to the first saved sheet. Any help will be greatly appreciated.
I am trying to use the following code for the above that I found in one of the MrExcel threads: It only works to save the first sheet. After that it gives Script out of range error pointing to the first saved sheet. Any help will be greatly appreciated.
VBA Code:
Dim Folder As String, FileName As String, FilePath As String, SheetName As String, Msg As String
Dim DestWB As Workbook
Folder = Workbooks(1).Path
If Folder = "" Then 'case when workbook is new and unsaved
Folder = CurDir$
End If
If Not Right(Folder, 1) = "\" Then
Folder = Folder & "\" 'add backslash if not present
End If
'FileName = "MyNewWorkbook.xlsx" 'name of new .xlsx workbook
FileName = ActiveSheet.Range("N1").Value 'name of new .xlsx found in cell N1
FilePath = Folder & FileName
SheetName = ActiveSheet.Name
'Debug code. These lines can be deleted later, once you have the functionality you want.
Msg = "Folder for " & ThisWorkbook.Name & " is" & vbCr & "'" & Folder & "'"
Msg = Msg & vbCr & vbCr & "File name: " & FileName
Msg = Msg & vbCr & vbCr & "New file to be created: " & vbCr & "'" & FilePath & "'"
If MsgBox(Msg & vbCr & vbCr & "Proceed?", vbOKCancel Or vbQuestion, "Debug Information") = vbCancel Then
Exit Sub
End If
'End debug
Sheets("Sheet18").Select
If IsEmpty(Range("A2").Value) = False Then
Sheets("Sheet18").Move
End If
Set DestWB = ActiveWorkbook
Application.DisplayAlerts = False
DestWB.SaveAs FileName:=FilePath, FileFormat:=xlOpenXMLWorkbook
DestWB.Close True
Application.DisplayAlerts = True
MsgBox "Worksheet " & SheetName & " saved to new workbook:" & vbCr & FilePath, vbOKOnly Or vbInformation, Application.Name
Workbooks(1).Activate
Sheets("Sheet17").Select
If IsEmpty(Range("A2").Value) = False Then
Sheets("Sheet17").Move
End If
Set DestWB = ActiveWorkbook
Application.DisplayAlerts = False
DestWB.SaveAs FileName:=FilePath, FileFormat:=xlOpenXMLWorkbook
DestWB.Close True
Application.DisplayAlerts = True
MsgBox "Worksheet " & SheetName & " saved to new workbook:" & vbCr & FilePath, vbOKOnly Or vbInformation, Application.Name
Workbooks(1).Activate