Change and define code by sheets names with vba code - excel

Currently I have this code below:
Sub EXCELS()
'Create excel files
Dim i As Integer
Dim name_file As String
For i = 5 To Sheets.Count
name_file = Sheets(i).Name
Worksheets(i).Copy
With ActiveWorkbook
.SaveAs Filename:="C:\Users\marya\OneDrive - Desktop\Cantina\listas" & "\" &
name_file & ".xlsx", FileFormat:=xlOpenXMLWorkbook
.Close SaveChanges:=False
End With
Next i
End Sub
I would like to change and define this code below by sheets names, as "Lista_AA", "Lista_BB". Instead of creating excel files from sheet 5, create excel files that contain the names "Lista_AA", "Lista_BB"...
For i = 5 To Sheets.Count
Error:

It's not clear how we know which sheets should be exported to their own workbooks. This answer assumes that you want to export each sheet that has a name starting with "Lista_", so that would export "Lista_AA", "Lista_BB" but not "Meal_Register"
Sub EXCELS()
'Create excel files
Dim i As Integer
Dim name_file As String
For i = 1 To Worksheets.Count
name_file = Sheets(i).Name
If Left(name_file, 6) = "Lista_" Then
Worksheets(i).Copy
With ActiveWorkbook
.SaveAs Filename:="C:\Users\marya\OneDrive - Desktop\Cantina\listas\" & _
name_file & ".xlsx", FileFormat:=xlOpenXMLWorkbook
.Close SaveChanges:=False
End With
End If
Next i
End Sub
If there is a different pattern for the sheet names, or if you want to specify a list of sheet names to export, please make a comment below and I'll amend or make a new answer.

Here's a version that will overwrite existing workbooks with the same name without prompting the user
Sub EXCELS()
'Create excel files
Dim i As Integer
Dim name_file As String
Dim file_path as String
Application.DisplayAlerts = False
For i = 1 To Worksheets.Count
name_file = Sheets(i).Name
If Left(name_file, 6) = "Lista_" Then
Worksheets(i).Copy
file_path = "C:\Users\marya\OneDrive - Desktop\Cantina\listas\" & name_file & ".xlsx"
' try to delete a file that has the same name as the one we are about to save
on error resume next
kill file_path
on error goto 0
debug.print file_path
With ActiveWorkbook
.SaveAs Filename:=file_path, FileFormat:=xlOpenXMLWorkbook
.Close SaveChanges:=False
End With
End If
Next i
End Sub

Related

VBA Run-Time Error '1004': can't paste because area not the same

I'm trying to de-bug some VBA code and haven't been able to hit on the right terms. I'm attempting to copy multiple rows and columns from multiple sheets into one master sheet. I know the issue is that I'm seleting too large of an area to copy and paste, but could use some help refining the code to only select and paste the data I need. Any help appreciated!
What I have now:
Sub OpenXML()
'
'Use this macro to open XML 2003 docs and save them as XLSX and combine them into one XLSX doc
'
Dim wbTemp, wbSave As Workbook
Dim count As Long
Dim xmlFilePath, saveFilePath, fileName As String
Set wbSave = Workbooks.Add
count = 1
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'======>>>____Update file paths here____<<<======
xmlFilePath = [withheld]
saveFilePath = [withheld]
file = Dir(xmlFilePath & "*.xml")
fileNameNoExt = Left(file, Len(file) - 4)
'Loop to open the XML file, save a copy as XLSX, AND create a combined file with all data
Do While Len(file) > 0
'Open each XML file
Set wbTemp = Workbooks.Open(fileName:=xmlFilePath & file)
'Save as XLSX
ActiveWorkbook.SaveAs fileName:=saveFilePath & fileNameNoExt & ".xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
'Copy data from each XML into one main XLSX
wbTemp.Sheets(2).Select
If count = 1 Then 'take only 1 header row
Rows("1:1").Select
Else
Rows("2:2").Select
End If
Range(Selection, ActiveCell.End(xlDown)).Select
Selection.Copy wbSave.Sheets(1).Cells(count, 1)
wbTemp.Close
count = wbSave.Sheets(1).UsedRange.Rows.count + 1
'Prep for next file
file = Dir
If Len(file) > 0 Then
fileNameNoExt = Left(file, Len(file) - 4)
End If
Loop
wbSave.SaveAs fileName:=saveFilePath & "AllSheetsCombined.xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
wbSave.Close
End Sub
I tried something similar to
Sub SelectRangeDown()
Range("c1", Range("c1").End(xlDown)).Select
End Sub
but did did not work
Consider using UsedRange
Option Explicit
Sub OpenXML()
'
'Use this macro to open XML 2003 docs and
'save them as XLSX and combine them into one XLSX doc
'======>>>____Update file paths here____<<<======
Const xmlFilePath = "" '[withheld]
Const saveFilePath = "" '[withheld]"
Const xmlsheet = 2
Dim wbTemp As Workbook, wbSave As Workbook
Dim rngSource As Range, rngTarget As Range
Dim fileName As String, fileNameNoExt As String
Dim h As Long, n As Long
Set wbSave = Workbooks.Add
Set rngTarget = wbSave.Sheets(1).Range("A1")
'Loop to open the XML file, save a copy as XLSX,
' AND create a combined file with all data
Application.ScreenUpdating = False
h = 0 ' header offset
fileName = Dir(xmlFilePath & "*.xml")
Do While Len(fileName) > 0
fileNameNoExt = Left(fileName, Len(fileName) - 4)
'Open each XML file
Set wbTemp = Workbooks.Open(fileName:=xmlFilePath & fileName, ReadOnly:=True)
With wbTemp
'Copy data from each XML into one main XLSX
With .Sheets(xmlsheet).UsedRange
Set rngSource = .Offset(h).Resize(.Rows.count - h)
rngSource.Copy rngTarget
Set rngTarget = rngTarget.Offset(rngSource.Rows.count)
End With
'Save as XLSX
.SaveAs fileName:=saveFilePath & fileNameNoExt & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
.Close
End With
' next file
h = 1 ' no header after first file
n = n + 1
fileName = Dir
Loop
Application.ScreenUpdating = True
wbSave.SaveAs fileName:=saveFilePath & "AllSheetsCombined.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
wbSave.Close SaveChanges:=False
MsgBox n & " files combined", vbInformation
End Sub

Export csv separated by columns

I have an Excel with several sheets I want to export to csv delimited by columns.
When I run the code, it exports the files to csv but comma delimited, not column delimited as I export in csv.
Any help would be appreciated.
Sub SaveShtsAsBook()
Dim Sheet As Worksheet, SheetName$, MyFilePath$, N&
MyFilePath$ = ActiveWorkbook.path & "\" & _
Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 5)
With Application
.ScreenUpdating = False
.DisplayAlerts = False
' End With
On Error Resume Next '<< a folder exists
MkDir (MyFilePath & "_csv") '<< create a folder
For N = 1 To Sheets.Count
Sheets(N).Activate
SheetName = ActiveSheet.Name
Cells.Copy
Workbooks.Add (xlWBATWorksheet)
With ActiveWorkbook
With .ActiveSheet
.Paste
.Name = SheetName
[A1].Select
End With
'save book in this folder
.SaveAs ThisWorkbook.path & "\_csv\" & SheetName & ".csv", FileFormat:=xlCSV
.Close SaveChanges:=True
End With
.CutCopyMode = False
Next
End With
Sheet1.Activate
End Sub
Thanks!
Edit: Screenshot that clarifies my problem.
https://imgur.com/a/mPn997B
Define FileFormat as xlText and the file will be TAB delimited, which you obviously are looking for.
f.ex.:
Private Sub CommandButton1_Click()
Dim wb As Workbook
Set wb = ActiveWorkbook
wb.SaveAs "c:\tmp\tabtest.csv", xlText
End Sub

Why won't ActiveSheet.Name function work in vba?

I want to create a new (separate) workbooks for each worksheets from Test_Main but I am getting a
1004 error
in this line of code stating that I need a new name and cannot use this name as it is in use.
wb.SaveAs "H:\IT\Melissa\Essengeld\TEST" & "\" & ActiveSheet.Name & ".csv"
Is my code right? Or is there any other alternative for this ?
Thanks in advance !
Private Sub CommandButton3_Click()
Dim a As Integer
Dim ws As Worksheet
Dim wb As Workbook
a = ThisWorkbook.Worksheets.Count 'counts all the sheets
For i = 1 To a 'loops for all sheets
If ThisWorkbook.Worksheets(i).Name <> "Test_Main" Then 'rule out the main sheet
Set wb = Workbooks.Add
ThisWorkbook.Worksheets(i).Copy before:=wb.Worksheets(1) 'new workbook has 1 worksheet by deafult
wb.SaveAs "H:\IT\Melissa\Essengeld\TEST" & "\" & ActiveSheet.Name & ".csv"
wb.Close savechages = True
End If
Next i
ThisWorkbook.Activate
ThisWorkbook.Sheets(1).Activate
ThisWorkbook.Sheets(1).Cells(1, 1).Select
MsgBox ("Task Completed")
End Sub

Save SPREADSHEETS in multiple excel files with the name of the main file

I have an Excel file with 4 auxaliary sheets + 7 sheets with tables.
I would like to copy and separate each sheet (of the 7 sheets) into multiple excel's, so that each excel file has only 1 table. These sheets starts with "Lista", as for example "Lista_AA", "Lista_BB"...
After I would like to save these sheets with same name they had in the main excel.
I don't have code because I try with with macro recorder and didn't function.I have already looked for several videos and questions on this site and they are a little different from what I want
I have this code for create these sheets in pdf:
Sub excels()
Application.ScreenUpdating = False
Dim i As Integer
Dim nome_arquivo As String
For i = 5 To Sheets.Count
nome_arquivo = Sheets(i).Name
With Sheets(i)
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & "\" & nome_arquivo & ".pdf"
End With
Next i
Application.ScreenUpdating = True
End Sub
Is it possible to adapt for Excel files for same sheets?
Use a loop:
Const filepath As String = "https://agits-my.sharepoint.com/personal/Documents/Desktop/Cantina/"
Sub macro()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "Lista_*" Then
SaveCopy ws:=ws
End If
Next
End Sub
Private Sub SaveCopy(ByVal ws As Worksheet)
ws.Copy
Dim wb As Workbook
Set wb = ActiveWorkbook
wb.SaveAs FileName:=filepath & ws.Name & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, _
CreateBackup:=False
wb.Close SaveChanges:=False
End Sub

Merge a list of excel files into a new excel book

I need to create a macro that merges a list of excel files in a directory.
The folder contains other files that I don't want to pick. So, I need to specify the list of files (such as, selecting all the files which name contains "02.08.xlsx").
This is my first time using VBA, so please take that into consideration.
I've tried some things, but I think I always get problems regarding the files selection.
Here's what I've tried so far, but not working:
Sub MergeWorkbooks()
Dim FolderPath As String
Dim Filename As String
Dim ListFilenames As Variant
Dim Sheet As Worksheet
Application.ScreenUpdating = False
FolderPath = CurDir()
ListFilenames = Array("*02.08.02.01*.xlsx", "*02.08.13.01*.xlsx")
For i = 1 To 2
Filename = Dir(FolderPath & ListFilenames(i))
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Next i
Application.ScreenUpdating = True
End Sub
The code is wouldb be like this.
Sub MergeWorkbooks()
Dim FolderPath As String
Dim Filename As String
Dim ListFilenames As Variant
Dim Sheet As Worksheet
Application.ScreenUpdating = False
FolderPath = CurDir()
ListFilenames = Array("*02.08.02.01*.xlsx", "*02.08.13.01*.xlsx")
For i = 0 To 1
Filename = Dir(FolderPath & "\" & ListFilenames(i))
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & "\" & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
Next i
Application.ScreenUpdating = True
End Sub
Use the AddIn from the link below.
https://www.rondebruin.nl/win/addins/rdbmerge.htm
That will do what you want.

Resources