How to assingn my code properly to a button? - excel

This code works perfectly it saves an excel file to CSV-UTF8 and adds a timestamp in front of the file named "Test".
However, when I assign this code to a button, I'm always getting an error 400 for some reason.
So what I did is put the same code inside a module and debug it, and it didn't give me any errors it executed the code without any problems.
Can someone help me get this to work while using a button?
Sub SaveWorkSheetAsCSV()
Dim wbNew As Excel.Workbook
Dim wsSource As Excel.Worksheet, wsTemp As Excel.Worksheet
Dim name As String, myPath As String
comp = Environ("username")
myPath = "C:\" & comp & "\Testing\" 'use here the path you need
Set wsSource = ThisWorkbook.Worksheets(1)
name = Format(Now, "yyyymmdd-hh.mm") & " Testing"
Application.DisplayAlerts = False 'will overwrite existing files without asking
Set wbNew = ActiveWorkbook
wbNew.SaveAs myPath & "\" & name & ".csv", xlCSVUTF8 'new way
wbNew.Close
Application.DisplayAlerts = True
End Sub
Error 1004
Recieving the following error on this part:
wbNew.SaveAs myPath & "\" & name & ".csv", xlCSVUTF8 'new way

Export to CSV
'Semicolon users' might want to add , Local:=True to the SaveAs line to get the result separated by the semicolon.
ThisWorkbook.FollowHyperlink FolderPath will open the folder in Windows File Explorer.
The Code
Option Explicit
Sub SaveWorkSheetAsCSV()
Dim FolderPath As String
FolderPath = Environ("USERPROFILE") & "\Testing"
' or:
'FolderPath = "C:\Users\" & Environ("USERNAME") & "\Testing"
' Print the path to the Immediate window (CTRL+G).
'Debug.Print FolderPath
Dim FileName As String: FileName = Format(Now, "yyyymmdd-hh.mm ") & " Test"
Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets(2)
Application.ScreenUpdating = False
sws.Copy
Dim dwb As Workbook: Set dwb = ActiveWorkbook
Application.DisplayAlerts = False
dwb.SaveAs FolderPath & "\" & FileName & ".csv", xlCSVUTF8 ', Local:=True
Application.DisplayAlerts = True
dwb.Close SaveChanges:=False
Application.ScreenUpdating = True
'ThisWorkbook.FollowHyperlink FolderPath
End Sub

Related

Select and save specific sheets as new workbook

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

Excel VBA - Opened workbook with wildcard or partial match cannot save as copy

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

Export several sheets VBA

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

Copy worksheet into new workbook and save

Copy Worksheet 1 in Workbook A
Create new Workbook (named as below)
Copy worksheet 1 into new workbook
Save new workbook as 'abc (daily) & Format(Date, "ddmmmyyy") & ".xlsm" - i.e. code will save in a way that depends on today's date
I'm not sure where I'm making a mistake
'Save Worksheet1 as Workbook
Worksheets("Worksheet 1").Activate
With Worksheets("Worksheet 1")
.copy
End With
saveLocation = "X:\abc\abc\abc (daily)" & Format(Date, "ddmmmyyy") & ".xlsm"
ActiveSheet.ExportAsFixedFormat Type:=xlTypexlsm, _
Filename:=saveLocation
Sub CopySheetAsNewWorkbook()
Dim theNewWorkbook As Workbook
Dim currentWorkbook As Workbook
'currentWorkbook is the source workbook, create a new workbook referencing to it with theNewWorkbook
Set currentWorkbook = ActiveWorkbook
Set theNewWorkbook = Workbooks.Add
'do the copy (it's better to check if there is already a 'Worksheet 1' in the new workbook. It it exists delete it or rename it
currentWorkbook.Worksheets("Worksheet 1").Copy before:=theNewWorkbook.Sheets(1)
'Remove default sheets in order to have only the copied sheet inside the new workbook
Application.DisplayAlerts = False
Dim i As Integer
For i = theNewWorkbook.Sheets.Count To 2 Step -1
theNewWorkbook.Sheets(i).Delete
Next i
Application.DisplayAlerts = True
'Save File as XLSM
saveLocation = "X:\abc\abc\abc (daily)" & Format(Date, "ddmmmyyy") & ".xlsm"
theNewWorkbook.SaveAs Filename:=saveLocation, FileFormat:=XlFileFormat.xlOpenXMLWorkbookMacroEnabled
theNewWorkbook.Close
End Sub
Maybe try something like this:
Sub test()
Path = "D:\"
Filename = "test "
Sheets("Worksheet 1").Copy
' for multiple sheets : Sheets(Array("TABEL", "DATA", "BACKUP")).Copy
' to save with time : ActiveWorkbook.SaveAs Filename:=Path & Filename & Format(Now(), "yymmdd hh mm ss") & ".xlsm", FileFormat:=52
ActiveWorkbook.SaveAs Filename:=Path & Filename & Format(Date, "ddmmyy") & ".xlsm", FileFormat:=52
ActiveWorkbook.Close
End Sub
A Worksheet Export
Before running the code, adjust the values of variables NewFilePath
and SourceSheet in Sub exportFirst. NewFilePath must not end with a backslash \.
The code is written to refer to a worksheet in ThisWorkbook i.e. the workbook
containing this code.
Sub exportFirst is calling Sub exportWorksheet.
You can write several subs like Sub exportFirst for other
worksheets in the workbook.
I would prefer using e.g. Worksheets("Sheets1") over
Worksheets(1).
After you are done testing the code, you should probably un-comment the
line .Close.
Option Explicit
Sub exportFirst()
Const NewFilePath As String _
= "C:\Test"
Dim SourceSheet As Worksheet
Set SourceSheet = ThisWorkbook.Worksheets(1)
exportWorksheet SourceSheet, NewFilePath
End Sub
Sub exportWorksheet(SourceSheet As Worksheet, NewFilePath As String)
Dim NewFileName As String
Dim SaveLocation As String
' Either:
' ' If you want to name the new workbook using 'SourceSheet.Name':
NewFileName = SourceSheet.Name
' ' Or:
' ' If you want to name the new workbook using 'ThisWorkbook.Name':
' NewFileName _
' = Left$(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, ".") - 1)
' I would prefer "yyyymmdd" or at least "ddmmmyyyy"
SaveLocation = NewFilePath & "\" & NewFileName & " (daily)" _
& Format(Date, "ddmmmyyy")
SourceSheet.Copy
With ActiveWorkbook
' Either:
' .xlsm
SaveLocation = SaveLocation & ".xlsm"
.SaveAs FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
Filename:=SaveLocation
' or:
' .xlsx
' SaveLocation = SaveLocation & ".xlsx"
' .SaveAs FileFormat:=xlOpenXMLWorkbook, _
' Filename:=SaveLocation
' or:
' .csv
' SaveLocation = SaveLocation & ".csv"
' .SaveAs FileFormat:=xlCSVUTF8, Filename:=SaveLocation
' or:
' .pdf
' SaveLocation = SaveLocation & ".pdf"
' .ExportAsFixedFormat Type:=xlTypePDF, Filename:=SaveLocation
' .Saved = True
'.Close ' You should use '.Close' always with '.pdf'.
End With
End Sub

Subscript out of range error 9 vba

I am getting a subscript out of range error when another user runs my add in but have no problems when running the same code myself. This happens when setting a workbook value. The filename is being generated by getting the current date and stored as gendate. From this, the filename is created and saved based on the filepath that the user has made. In this example, the value of gv.Range("b2").text is C:\Users\username\Desktop\ReportGeneration. fp is therefore C:\Users\dmulhausen\Desktop\ReportGeneration\TSReports9_6_201615h5m32s.xlsx
This is not generating an error for me, but it is generating an error for another user of the script.
Dim ai As Workbook 'add in data ---Initialized in Report Setup
Dim dwb As Workbook 'destination workbook ---Initialized in Report Setup
Dim ss As Worksheet 'source sheet
Dim ds As Worksheet 'destination sheet or writing sheet
Dim rv As Worksheet 'reporting variables sheet ---Initialized in Report Setup
Dim pv As Worksheet 'ts variables sheet ---Initialized in Report Setup
Dim gv As Worksheet 'global ai variables ---Initialized in Report Setup
Dim tempstr As String
Dim fp As String 'file path ---Initialized in Report Setup
Dim gendate As Date
Dim reportscreated As Integer
Dim initialized As Boolean
Dim sheetnames(1 To 12) As String
Sub reportsetup()
Set ai = Workbooks("TSReports add in.xlam")
Set rv = ai.Worksheets("ReportVars")
Set pv = ai.Worksheets("TS1_2Vars")
Set gv = ai.Worksheets("globalVars")
If (IsEmpty(gv.Range("b2").Value)) Then
MsgBox ("Please select a designated folder for reports")
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
gv.Range("b2").Value = .SelectedItems(1)
End If
ai.Save
End With
End If
initialized = True
gendate = Now()
tempstr = "TSReports" & Month(gendate) & "_" & Day(gendate) & "_" & Year(gendate) & Hour(gendate) & "h" & Minute(gendate) & "m" & Second(gendate) & "s"
fp = gv.Range("b2").Text & "\" & tempstr & ".xlsx"
Workbooks.Add
Application.DisplayAlerts = False
Application.AlertBeforeOverwriting = False
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=fp
Set dwb = Workbooks(tempstr) '*******Error occurs here*******
See: Windows().Activate works on every computer except one
This should fix the issue.
tempstr = "TSReports" & Month(gendate) & "_" & Day(gendate) & "_" & _
Year(gendate) & Hour(gendate) & "h" & Minute(gendate) & "m" & _
Second(gendate) & "s" & ".xlsx"
fp = gv.Range("b2").Text & "\" & tempstr
Workbooks.Add
Application.DisplayAlerts = False
Application.AlertBeforeOverwriting = False
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=fp
Set dwb = Workbooks(tempstr)
However this would be more robust:
Set dwb = Workbooks.Add
Application.DisplayAlerts = False
Application.AlertBeforeOverwriting = False
Application.DisplayAlerts = False
dwb.SaveAs Filename:=fp

Resources