Run-time error 1004 in Excel macro - excel

I have an excel file that I use to create invoices and a macro used to save the workbook to a new file and cleared contents etc ready for the next invoice input.
Since upgrading to Windows 10 and MS Office 365 the macro has stopped working. I am far from an expert, I cobbled together several bits from the net and managed to create a macro that worked - before the upgrade!
I am getting a Run-time error "1004" Method 'Save As" of object '_workbook' failed.
The macro is
Sub NextInvoice()
Range("D3").Value = Range("D3").Value + 1
Range("B18:H43").ClearContents
End Sub
Sub SaveInvoiceNewName()
Dim NewFN As Variant
'Copy invoice to a new workbook
ActiveSheet.Copy
NewFN = "C:\This PC\Documents\Brewing\Invoices\Invoice " & Range("C5").Value & Range("D3").Value & ".xlsm"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXLSMWorkbookMacroEnabled
ActiveWorkbook.Close
NextInvoice
End Sub

There is no such thing as xlOpenXLSMWorkbookMacroEnabled. I believe you meant xlOpenXMLWorkbookMacroEnabled.
'let the FileFormat add the appropriate file extension.
NewFN = "C:\This PC\Documents\Brewing\Invoices\Invoice " & Range("C5").Value & Range("D3").Value
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbookMacroEnabled
See xlFileFormat Enumeration.

Related

Why do I keep getting application-defined or object-defined error with simple VBA macro?

I am working on creating a macro to simplify things that I do on a daily basis. The idea behind this macro is to copy 7 worksheets from the parent report, open a new workbook, paste and hardcode the data, save it to my desktop and close the new workbook.
As I am working through debugging and testing my code I am running into a problem which I do not understand why it is happening. If I boot up windows and run the macro the first time in my excel workbook, I get no issues the first time I run it for the 7 reports. The problem comes up when I try to add code or fix issues and run the code again. I keep getting " Run-time error '1004' Application-defined or object defined error".
I am trying to debug and when I hit F8 for debugging and stepping into the code, it seems it gets hung up around step #4 when it is trying to close when I run it more than once. I am learning and using Leila Gharani's course, but I don't think I got this far in the course yet to understand. If someone can please help me so I can understand this concept, I would greatly appreciate it.
Thank you
'1. Select Parent Report and select BD Tab
Workbooks("Parent Report").Activate
Worksheets("BD").Select
'2. Select all cells from BD tab, open new workbook , paste data, and hardcode it.
Cells.Select
Cells.Copy
Workbooks.Add
Range("A1").PasteSpecial xlPasteAll
Cells.Select
Cells.Copy
Range("A1").PasteSpecial xlPasteValues
Cells.EntireRow.AutoFit
'3. Rename worksheet to BD and cell "A2" to BD.
ActiveWorkbook.ActiveSheet.Name = "BD"
Range("A2").Value = "BD"
Range("A1").Select
'4. Save current flash report to local drive, with monthly naming format and close it.
ActiveWorkbook.SaveAs "C:\Users\mylocaldriveinfo\Desktop\Flash Reports" & "\BD Monthly Reporting - Preliminary " & Format(Date, "mmm") & " " & Format(Date, "yyyy")
ActiveWorkbook.Close
I just figured it out. It was my one drive at work giving me an issue. I disabled it, as I never use it and doing so I have not been able to replicate the error.
I am sure this code isn't best practice, but it works for now.
Option Explicit
Sub CopySheets()
Const FOLDER = "C:\Users\mylocaldriveinfo\Desktop\Flash Reports\BD Monthly Reporting -"
Dim wbNew As Workbook, wbMaster As Workbook, sht, n As Long
Set wbMaster = ThisWorkbook
' create new workbook
Set wbNew = Workbooks.Add(1) ' 1 sheet
n = 1
For Each sht In Array("BD", "Sheet2", "Sheet3", "Sheet4", _
"Sheet5", "Sheet6", "SHeet7") ' 7 sheet names
wbMaster.Sheets(sht).Copy After:=wbNew.Sheets(n)
n = n + 1
With wbNew.Sheets(n)
.UsedRange.Value = .UsedRange.Value
.Range("A2") = sht
End With
Next
With wbNew
' delete blank sheet
Application.DisplayAlerts = False
.Sheets(1).Delete
Application.DisplayAlerts = True
' save
.SaveAs Filename:=FOLDER & Format(Date, "mmm yyyy")
.Close
End With
MsgBox "Done", vbInformation
End Sub

How to save file without the Excel VBA code in it?

Below is my code for saving the file without the VBA codes.
It saves together with the VBA codes.
Sheets.Select
Cells.Copy
Cells.PasteSpecial xlPasteValues
Application.DisplayAlerts = False
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C",
FileFormat:=xlExcel8
Application.DisplayAlerts = True
Next x
End Sub
Save your project as xlsx instead of xlsm then the Code shouln'd be saved
you could first copy sheets in a new workbook and then save it
Sheets.Copy
Sheets.Select
Cells.Copy
Cells.PasteSpecial xlPasteValues
Application.CutCopyMode = False
With ActiveWorkbook
Application.DisplayAlerts = False
.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C.xlsx"
Application.DisplayAlerts = True
.Close True
End With
from
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C", FileFormat:=xlExcel8
to this:
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C" & ".xlsx", FileFormat:=xlOpenXMLWorkbook
SaveAs Confusion
I'm confused, too. As it happens, when you save your macro enabled workbook (.xlsm) as macro not-enabled workbook (.xlsx), the workbook stays open still having the code in it. But the good thing is that it is saved without code. You can now save it, 'manually' SaveAs it, it will still be without code (macros) the next time you open it.
The code should demonstrate the following:
It is good practice to start with Option Explicit which will help
you by alerting you when something is wrong.
It is good practice to use constants at the beginning of the code,
especially for such long file paths, so when you have to change them
you can easily find them.
When you disable an event, there is a possibility you won't be able
to enable it again if you're not careful. If an error occurs, you should redirect
the code to enable those events again.
If you want to close the workbook, then use the line ThisWorkbook.Close
Option Explicit
Sub SaveMacroDisabled()
Const strPath = "I:\Excel\MyDocuments\Test\Test4\"
Const strXLSX = "BookMacroDisabled"
On Error GoTo ProgramError
Application.DisplayAlerts = False
ThisWorkbook.SaveAs strXLSX, _
FileFormat:=xlWorkbookDefault
SafeExit:
Application.DisplayAlerts = True
' ThisWorkbook.Close
Exit Sub
ProgramError:
MsgBox "An unexpected error occurred"
On Error GoTo 0
GoTo SafeExit
End Sub

VBA code to make a backup in the Sharepoint before closing workbook

I would like to have a vba code which automatically makes the backup to a Folder in the SharePoint. I have found a Code which makes a duplicate file within the hard disk but not in SharePoint.
SharePoint link(https://web-mp01/sites/5034/SitePages/Home.aspx), I Need to do backup in this link.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.DisplayAlerts = False
ActiveWorkbook.SaveCopyAs Filename:="C:\TEMP\" & _
TesStr & "-" & TesStr & "-" & ActiveWorkbook.Name
ActiveWorkbook.Save
Application.DisplayAlerts = True
End Sub

Export to CSV without opening

I am using an Excel Macro that detects two worksheets and writes them to CSV format in their current SharePoint directory. However, upon executing the macro, it proceeds to open the newly created files within the same workbook and gives me the following error:
Run-time error '1004':
Sorry, we couldn't find C:\ProgramFiles(x86)\Google\Chrome\Application...
Is it possible it was moved, renamed or deleted?
Can I perform the "Save As" without opening the new file and avoiding the given error?
To be clear, it performs the core function just fine, as the new CSV files are properly written to the Sharepoint folder, I simply want to avoid the error message.
Macro code is as below:
Sub Export()
'
' Export Macro
' Export Rules and Privileges to 'Rules.csv' and Privileges.csv'
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim ws As Worksheet
Dim path As String
path = ActiveWorkbook.path & "\"
For Each ws In Worksheets
If ws.Name Like "Rules" Then
ws.Activate
ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
If ws.Name Like "Privileges" Then
ws.Activate
ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
Next
Range("B9").Select
Application.Run "RulesWorkbook.xlsm!Export"
Range("B4").Select
End Sub
Thank you to FreeMan for the solution in getting rid of the error message. While I did not figure out how to prevent Excel from opening the newly generated programs, I was able to side-step that by closing the workbook upon macro execution. Updated code for the macro is below:
Sub Export()
'
' Export Macro
' Export SecurityRules and Privileges to 'Rules.csv' and 'Privileges.csv'
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim ws As Worksheet
Dim path As String
path = ActiveWorkbook.path & "\"
For Each ws In Worksheets
If ws.Name Like "Rules" Then
ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
If ws.Name Like "Privileges" Then
ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
Next
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub

Excel 2016: Active worksheet is not the visible one

I have an Excel macro that creates another workbook for the user to modify. When I try to enter data in a cell in the new workbook, however, I get the error "The cell or chart you're trying to change is on a protected sheet." The sheet in the macro workbook is, in fact, protected, but that sheet is not visible at the time I get the error. When I try to close the visible, newly created workbook, it’s the macro workbook that closes. The last thing my macro does is activate the sheet in the new workbook. What do I have to do to make that work? Having the macro close its own workbook solves the problem, of course, but that’s not what I want to do, since the user needs another macro in the same workbook to process the changes on the new sheet.
The program has over 6000 lines of code (so far), but here is one of the routines that causes the problem.
Private Sub z3_BudgetPrepUpd()
'Build a new workbook initialized to let the user modify data
'for an existing fiscal-quarter budget.
'When this routine executes,
' UserForm1 is still active.
Dim strTracer As String 'error-handling tracer for this subroutine
Dim strFyrQtr As String
On Error GoTo abend
If blnAbort Then Exit Sub
If blnAbortGlobal Then Exit Sub
'Find out which ListBox item the user selected:
If UserForm1.ListBox1.ListCount < 1 Then GoTo aa9000 'ListBox is empty
If UserForm1.ListBox1.ListIndex < 0 Then 'No item selected
strMsgTitle = udtPrm.msgTtl
strMsgPrompt = "Please select a fiscal quarter to update."
Call z0_MsgBox
GoTo aa9000
End If
strFyrQtr = UserForm1.ListBox1.Value 'Selected item in ListBox
'Close UserForm1:
UserForm1.Hide
ThisWorkbook.Sheets(c_WKS_WELCOME).Activate
'Build the udtBgt() array with data for the specified quarter:
lngBgtHiNdx = -1
Call zz_GetBudgetForQtr(strFyrQtr)
If blnAbort Then GoTo aa9000
'Build a new workbook for the user to update budget amounts:
Workbooks.Add
Set wkbNewBook = ActiveWorkbook
'Save the names of the default worksheets
'so we can delete them later:
strDfltSheets() = z0_SheetNames(wkbNewBook)
'Build a worksheet with data from the udtBgt() array:
Call z3_BuildBudgetUpdSheet
If blnAbort Then GoTo aa9000
'Delete the default worksheets:
Call z0_DeleteSheets(wkbNewBook, strDfltSheets())
If blnAbort Then GoTo aa9000
wkbNewBook.Sheets(c_WKS_IPT_BUDGET).Activate
'Excel 2016 Bug:
'We need to close ThisWorkbook to allow the user
'to work with the book we just created:
Application.DisplayAlerts = False
ThisWorkbook.Close
aa9000:
Exit Sub
abend:
lngErr = Err.Number
strErr = Err.Description
blnAbort = True
Application.Cursor = xlDefault 'no more hourglass
strMsgTitle = "Program Error"
strMsgPrompt = "The following error occurred:" & Chr(10) & Chr(10) & _
"Error No. " & CStr(lngErr) & Chr(10) & _
"Error Description: " & strErr & Chr(10) & _
"Subroutine: z3_BudgetPrepUpd" & Chr(10) & _
"Tracer: " & strTracer
Call z0_MsgBox
Resume aa9000
End Sub
You use ThisWorkbook which I agree with. You use ActiveWorkbook which I hardly ever use.
I'd recommend using a variable to store reference to workbooks other than that which houses your code. So use
Dim wb As Excel.Workbook
Set wb = Application.Workbooks.Open("c:\test.xlsm") 'for opening
'* or
Set wb = Application.Workbooks.Add 'for creating a new one
'* or
Set wb = Application.Workbooks.Item("AlreadyOpen.xlsm") 'for referencing one already open
'* from hereon use wb instead of ActiveWorkbook
wb.Worksheets.Item(1).Visible = True
Thanks, everyone, for your interest and suggestions. I have solved the problem by redesigning the application without UserForms or external workbooks. Office 2016 has many issues, and perhaps this is one of them. In any case, I have no more time to research it.

Resources