I'm working on a macro in my Excel File.
I want to export six worksheets as new backup files.
There are several sheets that I also don't want to export.
When I run the code as it is now there is one/two sheets that are being exported while the remaining four aren't exported.
The two exported sheets are then also being closed after they are saved as a new file.
I hope someone is able to help me and give me advice and feedback.
Thanks in advance.
My code is:
'''
Sub SplitWorkbook2()
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim xWs As Worksheet
Dim xWb As Workbook
Dim xNWb As Workbook
Dim FolderName As String
Application.ScreenUpdating = False
Set xWb = Application.ThisWorkbook
DateString = Format(Now, "mm-dd hh-mm")
FolderName = "I:\Export\Backup\TEMPS\2021\Urenlijsten\" & " Werkbriefjes week " & Range("C4") & " " & DateString
MkDir FolderName
Application.DisplayAlerts = False
On Error GoTo NErro
DoNotInclude = "Actions" & "Adressbook" & "Import" & "Hours_Database"
FileExtStr = ".xls"
For Each xWs In xWb.Sheets
If InStr(DoNotInclude, xWs.Name) = 0 Then
xWs.Copy
Set xNWb = Application.Workbooks.Item(Application.Workbooks.Count)
With xNWb
ActiveSheet.UsedRange.Value = ActiveSheet.UsedRange.Value
xFile = FolderName & "\" & Range("C6") & FileExtStr
xNWb.SaveAs xFile, FileFormat:=xlOpenXMLWorkbook
End With
End If
Next xWs
NErro: xWb.Activate
xWb.Activate
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "You can find the files in " & FolderName
End Sub
Export Worksheets
Not tested.
Option Explicit
Sub SplitWorkbook2()
Dim wb As Workbook
Dim ws As Worksheet
Dim DoNotInclude As Variant
Dim FileFormatNum As Long
Dim FileExtStr As String
Dim FolderName As String
FolderName = "I:\Export\Backup\TEMPS\2021\Urenlijsten\" & " Werkbriefjes week " & Range("C4") & " " & DateString
FileExtStr = ".xlsx" ' ??? not '.xls'
DateString = Format(Now, "mm-dd hh-mm")
DoNotInclude = Array("Actions" & "Adressbook" & "Import" & "Hours_Database")
On Error Resume Next
MkDir FolderName
On Error GoTo 0
Set wb = ThisWorkbook
Application.ScreenUpdating = False
For Each ws In wb.Worksheets
If IsError(Application.Match(ws.Name, DoNotInclude, 0)) Then
ws.Copy
With ActiveWorkbook.Worksheets(1)
.UsedRange.Value = .UsedRange.Value
xFile = FolderName & "\" & .Range("C6") & FileExtStr
Application.DisplayAlerts = False
.Parent.SaveAs xFile, FileFormat:=xlOpenXMLWorkbook
.Parent.Close
Application.DisplayAlerts = True
End With
End If
Next ws
Application.ScreenUpdating = True
MsgBox "You can find the files in " & FolderName
'wb.FollowHyperlink FolderName ' open in Windows File Explorer
End Sub
Related
I need to write a macro that allows me to select which workbook sheets I want to save as a new file separately.
I am currently doing it with the following code, but it saves all the sheets as a new file. I would like to be able to select or define which sheets I want to save.
Sub Save_sheets_xlsx()
Dim Path As String
Path = Application.ActiveWorkbook.Path
Dim FileName As String
FileName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs FileName:=Path & "\" & FileName & " " & xWs.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Export Sheets As New Workbooks
Option Explicit
Sub ExportSheets()
Const SheetNameList As String = "Sheet1,Sheet2,Sheet3" ' commas no spaces!
Dim SheetNames() As String: SheetNames = Split(SheetNameList, ",")
Dim FolderPath As String: FolderPath = ThisWorkbook.Path
Dim BaseName As String
BaseName = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 5)
Application.ScreenUpdating = False
Dim sh As Object
Dim FilePath As String
For Each sh In ThisWorkbook.Sheets(SheetNames)
sh.Copy
FilePath = FolderPath & "\" & BaseName & " " & sh.Name & ".xlsx"
Application.DisplayAlerts = False ' overwrite without confirmation
Workbooks(Workbooks.Count).SaveAs FileName:=FilePath
Application.DisplayAlerts = True
Application.ActiveWorkbook.Close SaveChanges:=False
Next
Application.ScreenUpdating = True
MsgBox "Sheets exported.", vbInformation
End Sub
I would like to open a workbook using a wildcard or partial name match and save a copy with another name.
However, there is an error -
Always at the " Workbooks(myFolderPath & "" & MyFileName).SaveCopyAs Filename:="NEW NAME.xlsx" " line
Here is my code:
Sub GENERATE()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'If workbook name like "Report Due" then open, if not already opened
Dim MyFileName As Variant
Dim myFolderPath As String
myFolderPath = Application.DefaultFilePath
MyFileName = Dir(myFolderPath & "\" & "Report Due*.xlsx")
If MyFileName <> "" Then
Workbooks.Open (myFolderPath & "\" & MyFileName)
End If
Workbooks(myFolderPath & "\" & MyFileName).SaveCopyAs Filename:="NEW NAME.xlsx"
Workbooks(myFolderPath & "\" & MyFileName).Close SaveChanges:=False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I'd be happy to see what's wrong! Many thanks!
Set a reference to the workbook when you open it, then you shouldn't need to use it's name to reference when saving the copy.
Option Explicit
Sub GENERATE()
Dim wb As Workbook
Dim MyFileName As Variant
Dim myFolderPath As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'If workbook name like "Report Due" then open, if not already opened
myFolderPath = Application.DefaultFilePath
MyFileName = Dir(myFolderPath & "\" & "Report Due*.xlsx")
If MyFileName <> "" Then
Set wb = Workbooks.Open(myFolderPath & "\" & MyFileName)
wb.SaveCopyAs Filename:="NEW NAME.xlsx"
wb.Close SaveChanges:=False
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I want to save Excel files in both the local drive and in the network folder. Currently I am doing it with SaveAs (local) and another SaveAs (network), is it faster to do a SaveAs then FileCopy?
Code below:
Sub SaveAs()
Dim ws As Worksheet
Dim ws_console As Worksheet
Dim long_col_number As Long
Dim long_sheets_count As Long
Dim arr_sheet_names As Variant
Dim str_password As String
Dim str_datetoday As String
Dim str_datetoday_path As String
Dim str_datetoday_network_path As String
str_datetoday = Format(Date, "yyyy-mm-dd")
str_datetoday_path = "C:\Users\" & Environ("Username") & "\Desktop\Report\" & str_datetoday
str_datetoday_network_path = "\\servername\data\reports\US Reports Daily\" & str_datetoday
If Dir(str_datetoday_path, vbDirectory) = "" Then
MkDir (str_datetoday_path)
MsgBox "Making directory"
End If
If Dir(str_datetoday_network_path, vbDirectory) = "" Then
MkDir (str_datetoday_network_path)
End If
For Each ws In ThisWorkbook.Worksheets
If ws.CodeName = "AILD_01_Console" Then
Set ws_console = ws
Exit For
End If
Next ws
long_col_number = 0
For long_col_number = 1 To 8
long_sheets_count = Application.WorksheetFunction.CountA(ws_console.Range(Cells(16, long_col_number), Cells(24, long_col_number)))
arr_sheet_names = ws_console.Range(Cells(16, long_col_number), Cells(15 + long_sheets_count, long_col_number))
arr_sheet_names = Application.WorksheetFunction.Transpose(arr_sheet_names)
Worksheets(arr_sheet_names).Copy
ActiveWorkbook.SaveAs _
Filename:=str_datetoday_path & "\" & ws_console.Cells(15, long_col_number) & " - " & Format(Date, "yyyy-mm-dd"), _
FileFormat:=51
ActiveWorkbook.SaveAs _
Filename:=str_datetoday_network_path & "\" & ws_console.Cells(15, long_col_number), _
FileFormat:=51
ActiveWorkbook.Close False
Next long_col_number
ws_console.Activate
End Sub
Thank you very much for all the help.
I'm encountering a error 438 when trying to confirm the expected values of variables.
The error is on line Debug.Print WBMaster. Only the code related to this question is shown.
Sub DSMReportsP02()
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim DistrictDSM As Range, DistrictsDSMList As Range
Set DistrictsDSMList = Range("E11:E" & Cells(Rows.Count, "E").End(xlUp).Row)
Dim Period As String, Path As String, DistPeriodFile As String, Territory As String
Dim YYYY As Variant
Dim WBMaster As Workbook, DistMaster As Workbook, CurDstTerrFile As Workbook
Dim wsCount As Integer, x As Integer
Dim wsExists As Boolean
Set WBMaster = ActiveWorkbook
Period = Range("C6").Value
YYYY = Range("C8").Value
wsExists = False
For Each DistrictDSM In DistrictsDSMList.Cells
Workbooks.Open Filename:="H:\Accounting\Monthend " & YYYY & "\DSM Files\DSM Master Reports\" & DistrictDSM & ".xlsx"
Set DistMaster = ActiveWorkbook
wsCount = Application.Sheets.Count
Path = "H:\Accounting\Monthend " & YYYY & "\DSM Files\" & DistrictDSM & "\P02"
DistPeriodFile = Dir(Path & "\*.xlsx")
Do While DistPeriodFile <> ""
Workbooks.Open Filename:=Path & "\" & DistPeriodFile, UpdateLinks:=False
DistPeriodFile = Dir
Set CurDstTerrFile = ActiveWorkbook
Territory = CurDstTerrFile.Sheets("Index").Range("A3").Value
Debug.Print WBMaster
Debug.Print DistrictDSM
Debug.Print DistMaster
Debug.Print wsCount
Debug.Print Path
Debug.Print DistPeriodFile
Debug.Print CusDstTerrFile
Debug.Print Territory
I made a macro that splits a main worksheet into different tabs and renames the tabs. I want to email the tabs to different people, by matching the tab name to a list containing email addresses.
What I have right now is this:
Sub Split_To_Workbook_and_Email_with_Body()
'Working in 2013/2016
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim sh As Worksheet
Dim DateString As String
Dim FolderName As String
Dim myOutlook As Object
Dim myMailItem As Object
Dim mySubject As String
Dim myto As String
Dim myPath As String
With Application
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
'Prompt for Email Subject
Set otlApp = CreateObject("Outlook.Application")
'mySubject = InputBox("Subject for Email")'this shows a dialog where you can enter the email subject (right now it is hard coded)
'myto = Application.VLOOKUP(SheetId, Sheet1!A3:B48, 2, FALSE)
'myto = Application.VLookup(SheetId, Sheet1!A3:B48, 2, range_lookup)
'Copy every sheet from the workbook with this macro
Set Sourcewb = ActiveWorkbook
'Create new folder to save the new files in
DateString = Format(Now, "yyyy-mm-dd hh-mm-ss")
FolderName = "Z:\user\report" & Sourcewb.Name & " " & DateString
MkDir FolderName
'Copy every visible sheet to a new workbook
For Each sh In Sourcewb.Worksheets
'If the sheet is visible then copy it to a new workbook
If sh.Visible = -1 Then
sh.Copy
'Set Destwb to the new workbook
Set Destwb = ActiveWorkbook
'Determine the Excel version and file extension/format
With Destwb
If Val(Application.Version) < 12 Then
'You use Excel 97-2003
FileExtStr = ".xls": FileFormatNum = -4143
Else
'You use Excel 2007-2016
If Sourcewb.Name = .Name Then
MsgBox "Your answer is NO in the security dialog"
GoTo GoToNextSheet
Else
FileExtStr = ".xlsx": FileFormatNum = 51
End If
End If
End With
'Change all cells in the worksheet to values if you want
If Destwb.Sheets(1).ProtectContents = False Then
With Destwb.Sheets(1).UsedRange
.Cells.Copy
.Cells.PasteSpecial xlPasteValues
.Cells(1).Select
End With
Application.CutCopyMode = False
End If
'Save the new workbook, email it, and close it
Set otlNewMail = otlApp.CreateItem(olMailItem)
With Destwb
.SaveAs FolderName _
& "\" & Destwb.Sheets(1).Name & FileExtStr, _
FileFormat:=FileFormatNum
End With
myPath = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
idkfile = "C:\Users\UniaHa\Desktop\Testing.txt"
With Destwb
.Close False
End With
With otlNewMail
'.Subject = mySubject
.to = test#test.ca
.Subject = "Diversion Report"
.Body = "Dear customer," & vbNewLine & vbNewLine & _
"This is your report please..... blah blah" & _
vbNewLine & vbNewLine & "Regards," & vbNewLine & vbNewLine & "Sender Name"
.Attachments.Add myPath
.Attachments.Add idkfile
.Display
End With
Set otlNewMail = Nothing
End If
GoToNextSheet:
Next sh
MsgBox "You can find the files in " & FolderName
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
End With
End Sub
For your vlookup, you can try something like:
On Error Resume Next
for each sht in activeworkbook.worksheets
err.clear
sEmailTo = Application.worksheetfunction.VLOOKUP(sh.name, Sheet1!A3:B48, 2, FALSE)
if err<>0 and semailto like "*#*" Then
'send your email
end if
next sht
On Error goto 0