Excel VBA - save as file with content from a specific sheet - vba

I'm trying to save as my Excel file into multiple xlsx files, soemthing like this:
I would like to save as it into multiple xlsx files with each file will content 1 line range("Ax:Dx"). I have written the code as below to do that
Sub split_file()
Dim wb As Workbook
Dim ws As Worksheet
Dim i As Long
Dim lastrow1 As Long
Dim lastrow2 As Long
Set wb = ThisWorkbook
On Error Resume Next
'Dim filename As String
Path = "C:\test"
For i = 2 To Sheet2.Range("A" & Rows.Count).End(xlUp).Row
'wb.Worksheets(3).Copy 'create new active workbook
Sheets.Add.Name = Sheet2.Range("A" & i).Value
With Worksheets(Sheet2.Range("A" & i).Value)
Range("A1:D1").Value = Sheet2.Range("A" & i & ":D" & i).Value
.SaveAs filename:=Path & "\" & Sheet2.Range("A" & i).Value, FileFormat:=xlOpenXMLWorkbook, Password:="Welcome1"
.Close savechanges:=False
End With
Next i
On Error GoTo 0
End Sub
The result I got is shown in this screenshot:
Once I open the file after save as with proper data, it include some unwanted sheets in that :( .
Like this:
I wish it save as only the file with the same name. Can anybody help look for this problem ?
Very appreciated for each support of you all.

Please, try the next way:
Sub split_file()
Dim wb As Workbook, ws As Worksheet, wsNew As Worksheet, wbNew As Workbook
Dim path As String, i As Long
Set wb = ThisWorkbook
Set ws = wb.Sheets(Sheet2.Name)
path = "C:\test"
For i = 2 To ws.Range("A" & rows.count).End(xlUp).row
Set wbNew = Workbooks.Add(xlWBATWorksheet)
Set wsNew = wbNew.Sheets(1): wsNew.Name = ws.Range("A" & i).value
wsNew.Range("A1:D1").value = ws.Range("A" & i & ":D" & i).value
wbNew.saveas FileName:=path & "\" & wsNew.Name, FileFormat:=xlOpenXMLWorkbook, password:="Welcome1"
wbNew.Close savechanges:=False
Next i
End Sub
I assumed that Sheet2 is a code name...

Related

VBA Export Sheets to Separate CSV Starting at Sheet 4 and beyond

as the title suggests, I'm trying to export sheets (starting from the fourth sheet and beyond, this is a fixed value) to separate CSV files. Ideally it would be right into a folder on the desktop containing each files. Below is the code I've been working with / trying to tweak-
Sub ExportSheetsToCSV()
Dim xWs As Worksheet
Dim xcsvFile As String
For Each xWs In Application.ActiveWorkbook.Worksheets
xWs.Copy
xcsvFile = CurDir & "\" & xWs.Name & ".csv"
Application.ActiveWorkbook.SaveAs Filename: = xcsvFile, _
FileFormat: = xlCSV, CreateBackup: = False
Application.ActiveWorkbook.Saved = True
Application.ActiveWorkbook.Close
Next
End Sub
Use the worksheets collection index.
Sub ExportSheetsToCSV()
Dim xWs As Worksheet
Dim xcsvFile As String, w as long
For w=4 to ActiveWorkbook.Worksheets.count
with ActiveWorkbook.Worksheets(w)
xcsvFile = CurDir & "\" & .Name & ".csv"
.Copy
with ActiveWorkbook
.SaveAs Filename:=xcsvFile, FileFormat:=xlCSV
.Close savechanges:=false
end with
end with
Next w
end sub
Is CurDir appropriate here? ActiveWorkbook.Path may be another option.

How to create new files from range

I would like to create new files (in the same folder) from sheet "lista strategiczna".D2 only if doesn't exist. Next offset one position down, and create next files etc. What I doing wrong?
Sub TworzenieZamowien()
Dim thisWb As Workbook
Dim nazwaPliku As String
Set thisWb = ActiveWorkbook
Dim aktywnaKomorka As Range
Set aktywnaKomorka = Sheets("lista strategiczna").Range("D2")
Dim FilePath As String
FilePath = Dir(ActiveWorkbook.Path, vbDirectory)
Do Until aktywnaKomorka = ""
nazwaPliku = thisWb.Path & "\Zamówienie " & aktywnaKomorka & ".xls"
If FilePath <> nazwaPliku Then
Workbooks.Add
ActiveWorkbook.SaveAs Filename:=nazwaPliku
ActiveWorkbook.Close savechanges:=False
aktywnaKomorka.Offset(1, 0).Select
Else
aktywnaKomorka.Offset(1, 0).Select
End If
Loop
End Sub
I would set your range at the start, use a For loop and do away with selecting things (rarely a good idea). Your current code doesn't change aktywnaKomorka(it remains D2), you just activate the next cell below but your loop does not reference the active cell.
Sub TworzenieZamowien()
Dim thisWb As Workbook
Dim nazwaPliku As String
Set thisWb = ActiveWorkbook
Dim aktywnaKomorka As Range
With Sheets("lista strategiczna")
Set aktywnaKomorka = .Range("D2", .Range("D" & Rows.Count).End(xlUp))
End With
Dim FilePath As String, r As Range
FilePath = Dir(ActiveWorkbook.Path, vbDirectory)
For Each r In aktywnaKomorka
If r <> vbNullString Then
nazwaPliku = thisWb.Path & "\Zamówienie " & r & ".xls"
If FilePath <> nazwaPliku Then
Workbooks.Add
ActiveWorkbook.SaveAs Filename:=nazwaPliku
ActiveWorkbook.Close savechanges:=False
End If
End If
Loop
End Sub
If you wanted to persist with your Do loop rather than Select add this line
set aktywnaKomorka=aktywnaKomorka.Offset(1, 0)

Code Improvement Needed

This is as far as I got with it however it is now only copying the active.sheet multiple times rather than cycling through.
The idea of what I was trying to achieve was for a macro to run and covert every worksheet as a .csv. The filename of that .csv would be the worksheet name which is decided by another macro than runs earlier in the flow.
Any ideas on how to circle through, as I said before. I am fairly new to code hence why I am asking.
Sub Export_Sub_Xpath()
'
' Export_Sub_Xpath Macro
'
Dim i As Integer
Dim WS_Count As Integer
Dim ws As Worksheet
WS_Count = ActiveWorkbook.Worksheets.Count
For i = 1 To WS_Count
Set ws = ThisWorkbook.Worksheets(i)
PathName = "" & ActiveWorkbook.Path & "\" & ws.Name & ".csv"
Columns("A:B").Select
Range("B3000").Activate
Selection.Copy
PathName = "" & ActiveWorkbook.Path & "\" & ws.Name & ".csv"
Workbooks.Add
ActiveSheet.Paste
Application.CutCopyMode = False
'ActiveWorkbook.SaveAs PathName = "" & ActiveWorkbook.Path & "\" & ws.Name & ".csv"
ActiveWorkbook.SaveAs Filename:=PathName, _
FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
Next i
End Sub
You forgot to activate each sheet before copying and saving. Try this:
Sub Export_Sub_Xpath() ' ' Export_Sub_Xpath Macro '
Dim i As Integer
Dim WS_Count As Integer
Dim ws As Worksheet
WS_Count = ThisWorkbook.Worksheets.Count
For i = 1 To WS_Count
Set ws = ThisWorkbook.Worksheets(i)
PathName = "" & ThisWorkbook.Path & "\" & ws.Name & ".csv"
ThisWorkbook.Worksheets(i).Activate ' You forgeot to Activate Each Sheet before saving
Columns("A:B").Select
Range("B3000").Activate
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWorkbook.SaveAs Filename:=PathName, _
FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close
Next i
End Sub

Excel VBA .SaveAs breaking in loop

I have an excel workbook broken out with multiple worksheets, 1 per customer. In my code, I am trying to save each individual customer worksheet as its own excel file. However, the .SaveAs command breaks the second time it triggers in the loop. Any pointers would be fantastic.
Dim SchedWorksheet As Worksheet
Dim SchedWorkbook As Workbook
Dim SchedName As String
Set SchedWorkbook = ActiveWorkbook
Set SchedWorksheet = ActiveSheet
Application.DisplayAlerts = False
For Each Worksheet In SchedWorkbook.Sheets
If Worksheet.Name = "Instructions" Or Worksheet.Name = "Invoice_Items"
Or Worksheet.Name = "Customers" Or _
Worksheet.Name = "Terms" Or Worksheet.Name = "Dilution_Type" Or
Worksheet.Name = "Approval_Status" Or _
Worksheet.Name = "Carriers" Then
GoTo NextSched
End If
If Worksheet.Name = "Invoices" Then
'basicScheduleFileName is global set at beginning of program
SchedName = basicScheduleFileName & "ALL"
Else
SchedName = Worksheet.Name
End If
'payoutFileName is global set at beginning of program
Worksheet.SaveAs Application.ActiveWorkbook.Path & "\" & payoutFileName
& "\Basic Schedule" & "\" & SchedName, xlOpenXMLWorkbook
NextSched:
Next Worksheet
The error on the second iteration is as follows:
Run-time error 1004 'Application-defined or object-defined error'
I have also attempted to run this loop using the SchedWorksheet object in lieu of Worksheet and get the error "method .SaveAs of object _Worksheet failed" on the second iteration.
Question I have code extremely similar to his code earlier in my program that takes a similar dataset and uses an exportAsFixedFormat call to save each worksheet as a PDF. Is there an equivalent for .xlsx? (.csv would be fine as well)
I don't know what value "payOutFileName" has so I left it out of the code. I also don't know the value for basicScheduleFileName so I set it to "Something." You will have to change that to whatever you need to change it too. This works fine when saving to my dir "C\Files" Might be a little buggy for you. Hopefully it will be a start.
Sub asdfghj()
Dim SchedWorkbook As Workbook
Dim SchedName As String
Dim basicScheduleFileName As String
Dim payoutFileName As String
Dim ws As Worksheet
Dim wb As Workbook
basicScheduleFileName = "Something"
Set SchedWorkbook = ActiveWorkbook
Application.DisplayAlerts = False
For Each ws In SchedWorkbook.Sheets
Debug.Print ws.Name
If ws.Name = "Instructions" Or ws.Name = "Invoice_Items" _
Or ws.Name = "Customers" Or _
ws.Name = "Terms" Or ws.Name = "Dilution_Type" Or _
ws.Name = "Approval_Status" Or _
ws.Name = "Carriers" Then
GoTo NextSched
End If
If ws.Name = "Invoices" Then
SchedName = basicScheduleFileName & "ALL" & ".xlsx"
Else
SchedName = ws.Name & ".xlsx"
End If
ws.Activate
' SaveAs Application.ActiveWorkbook.Path & "\" & payoutFileName & "\Basic Schedule" & "\" & SchedName, xlOpenXMLWorkbook
Set wb = Workbooks.Add
ws.Copy Before:=wb.Sheets(1)
wb.Sheets("Sheet1").Delete
wb.SaveAs Filename:="C:\Files\" & SchedName, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
wb.Close
NextSched:
Next ws
End Sub
First off, thanks to everyone who took time and brainpower trying to figure out my issue. I finally figured out a fix that works.
First I made sure to get rid of ActiveWorkbook and ActiveSheet references to avoid any confusion in Excel.
Second As #NickSlash pointed out, it was likely that even if my code did work, it would save multiple copies of the same file under different names. So, to solve that while fixing my original issue, I changed my code to copy the worksheets that I need into a new workbook and save them that way:
Dim WS As Worksheet
Dim WB As Workbook
Dim NWB As Workbook
Dim SchedName As String
Set WB = Workbooks("Basic_Schedule-.xls")
WB.Activate
'Application.DisplayAlerts = False
For Each WS In WB.Sheets
WB.Activate
If WS.Name = "Instructions" Or WS.Name = "Invoice_Items" Or WS.Name = "Customers" Or _
WS.Name = "Terms" Or WS.Name = "Dilution_Type" Or WS.Name = "Approval_Status" Or _
WS.Name = "Carriers" Then
GoTo NextSched
End If
If WS.Name = "Invoices" Then
SchedName = basicScheduleFileName & "ALL" & ".xlsx"
Else
SchedName = WS.Name & ".xlsx"
End If
'Copy sheet to another WB
Set NWB = Workbooks.Add
WB.Activate
Sheets(WS.Name).Copy After:=NWB.Sheets(NWB.Sheets.Count)
NWB.Sheets("Sheet1").Delete
NWB.SaveAs filename:=basicScheduleFilePath & "\" & payoutFileName & "\Basic Schedule" & "\" & SchedName
NWB.Close
WB.Activate
NextSched:
Next WS
Instead of this:
'Copy sheet to another WB
Set NWB = Workbooks.Add
WB.Activate
Sheets(WS.Name).Copy After:=NWB.Sheets(NWB.Sheets.Count)
NWB.Sheets("Sheet1").Delete
NWB.SaveAs filename:=basicScheduleFilePath & "\" & payoutFileName & "\Basic Schedule" & "\" & SchedName
NWB.Close
WB.Activate
Do this -- you can avoid the "Activate" method call, and also if you have a reference to WS as an object, it's redundant to do WB.Sheets(WS.Name) when WS already refers to the same Worksheet.
'Copy sheet to another WB
WS.Copy '## Creates a new workbook with the copied sheet.
Set NWB = ActiveWorkbook
NWB.SaveAs filename:=basicScheduleFilePath & "\" & payoutFileName & "\Basic Schedule" & "\" & SchedName
NWB.Close

break external links not working when used directly after creating a file

I have a code that copies two worksheets from one workbook to a new one.
Since those two worksheets contain graphs where the data is on the sheet itself, but the datacells refer to a different worksheet, I copy the values only, to avoid external links.
However I found out that there is still an external link to my original workbook.
I don't know where it is though, since there are no formulas anymore.
I thought about names and deleted them as well, since there were a lot of names, that didn't even exist in the original file. That didn't help either.
I can delete the external, when using the menu in the ribbon.
And the code below also works, when I use it in the new workbook itself when opening it and running it in there.
Sub BreakLinks()
Dim wb As Workbook
Set wb = Application.ActiveWorkbook
If Not IsEmpty(wb.LinkSources(xlExcelLinks)) Then
For Each link In wb.LinkSources(xlExcelLinks)
wb.BreakLink link, xlLinkTypeExcelLinks
Next link
End If
End Sub
However, if I want to use that code in conjunction with the copying, it does not do the trick. I saved it on purpose before breaking the link, because I thought it might not be able to do it, but it didn't help.
Does anybody know why it doesn't work or can point me to a solution?
Here's the complete code:
Sub ACTION_Export_Capex()
Dim Pfad As String
Dim Dateiname As String
Dim ws As Worksheet
Dim wb As Workbook
Pfad = "D:\#Inbox\"
Dateiname = Format(Date, "YYYY-MM-DD") & " " & Format(Time, "hhmm") & " " & "monthly Report-" & Format(DateSerial(Year(Date), Month(Date) - 1, 1), "yyyy-mm") & " Capex" & ".xlsx"
'Copy Sheets without formulas
Sheets(Array("Capex_monthly", "Capex_YTD")).Copy
For Each ws In Worksheets
ws.UsedRange = ws.UsedRange.Value
Next
'get rid of macrobuttons and hyperlinks
For Each ws In Worksheets
ws.Rectangles.Delete
ws.Hyperlinks.Delete
Next
ActiveWorkbook.SaveAs Filename:=Pfad & Dateiname, FileFormat:=xlOpenXMLWorkbook
'delete external links
If Not IsEmpty(ActiveWorkbook.LinkSources(xlExcelLinks)) Then
For Each link In ActiveWorkbook.LinkSources(xlExcelLinks)
ActiveWorkbook.BreakLink link, xlLinkTypeExcelLinks
Next link
End If
ActiveWorkbook.Save
ActiveWorkbook.Close
'go back to main menu in Cockpit
Sheets("Menu").Select
End Sub
Thanks a lot in advance.
EDIT:
In the end brettdj got the solution, I just had to tweak it a bit to get it done in my workbook.
Here's the code:
Sub ACTION_Export_Capex()
Dim Pfad As String
Dim Dateiname As String
Dim ws As Worksheet
Dim wb As Workbook
Pfad = "D:\#Inbox\"
Dateiname = Format(Date, "YYYY-MM-DD") & " " & Format(Time, "hhmm") & " " & "monthly Report-" & Format(DateSerial(Year(Date), Month(Date) - 1, 1), "yyyy-mm") & " Capex" & ".xlsx"
'Copy Sheets without formulas
Sheets(Array("Capex_monthly", "Capex_YTD")).Copy
For Each ws In Worksheets
ws.UsedRange = ws.UsedRange.Value
Next
'get rid of macrobuttons and hyperlinks
For Each ws In Worksheets
ws.Rectangles.Delete
ws.Hyperlinks.Delete
Next
'get rid of external link
ActiveWorkbook.ChangeLink ThisWorkbook.Name, ActiveWorkbook.Name, xlLinkTypeExcelLinks
ActiveWorkbook.SaveAs Filename:=Pfad & Dateiname, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
Sheets("Menu").Select
End Sub
If I use this code the links are gone when the new worbook is opened again.
I am still puzzled why the original creation builds in a phantom link that exists even when the two copied sheets are deleted.
code
Sub Test()
Dim wb As Workbook
Dim wb2 As Workbook
Dim Pfad As String
Dim Dateiname As String
Dim ws As Worksheet
With Application
.ScreenUpdating = False
.DisplayAlerts = falser
End With
Pfad = "D:\#Inbox\"
'Pfad = "c:\temp\"
Dateiname = Format(Date, "YYYY-MM-DD") & " " & Format(Time, "hhmm") & " " & "monthly Report-" & Format(DateSerial(Year(Date), Month(Date) - 1, 1), "yyyy-mm") & " Capex" & ".xlsx"
Set wb = ThisWorkbook
Set wb2 = Workbooks.Add(1)
wb.Sheets(Array("Capex_monthly", "Capex_YTD")).Copy After:=wb2.Sheets(1)
wb2.Sheets(1).Delete
wb2.SaveAs Filename:=Pfad & Dateiname, FileFormat:=xlOpenXMLWorkbook
wb2.ChangeLink wb.Name, wb2.Name, xlLinkTypeExcelLinks
wb2.Close
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.Goto wb.Sheets("Menu").[a1]
End With
Set wb2 = Workbooks.Open(Pfad & Dateiname)
End Sub