Macro gives error when updating connections - but only sometimes - excel

My macro opens up a couple of files, then updates Connections in one of those files. These connections are all pulls from website html tables. The macro worked just fine for a while. Now, when I run the macro, I get this error:
Run-time error '1004':
Application-defined or object-defined error
When debugging, the error points to the first connection update line of the macro (Advanced2). Here's the code:
Workbooks.Open (ThisWorkbook.Path & "\TheFormulaFinal V5.xlsm")
Workbooks.Open (ThisWorkbook.Path & "\WebScraper.xlsx")
Windows("WebScraper.xlsx").Activate
ActiveWorkbook.Connections("Advanced2").Refresh
ActiveWorkbook.Connections("DVP").Refresh
ActiveWorkbook.Connections("PrSolu").Refresh
ActiveWorkbook.Connections("Misc").Refresh
ActiveWorkbook.Connections("NF Project").Refresh
ActiveWorkbook.Connections("OppTot").Refresh
ActiveWorkbook.Connections("PlrTot2").Refresh
ActiveWorkbook.Connections("TeamTot").Refresh
ActiveWorkbook.Connections("RotoGuru").Refresh
Sheets("PlrTot2").Select
However, the very odd thing is that if I close the two files my code opened (WebScraper and TheFormula V5) without saving, then run the exact same macro, the next time it works! I suspect it has to be some kind of time-related error. I have turned off all background connection refresh as well as any kind of refresh upon file open, so none of these connections should ever update unless they are manually called to do so. I tried using Application Wait to add some time after the WebScraper file opened, and/or after the first refresh, but no avail. I also tried adding some dummy activities after the WebScraper file is activated to see if the file needed some time to load the connections, but also no luck.
Any help is appreciated, thanks!

Workbooks.Open function returns reference to opened workbook. You can use this reference instead ActiveWorkbook.
Dim wb As Workbook
Set wb = Workbooks.Open(ThisWorkbook.Path & "\WebScraper.xlsx")
wb.Connetions("Advanced2").Refresh
...

Related

UserInterfaceOnly = True is discarded when opening a file

I have an Excel+VBA file named "Myfile.xlsm" which needs that UserInterfaceOnly = True property so the VBA code can perform many operations without the user being aware.
I did place the following code to set UserInterfaceOnly = True property in the Workbook_Open event (also tried in the Workbook_Activate event) of "Myfile.xlsm".
Private Sub Workbook_Open()
Dim WSh As Worksheet
For Each WSh In ThisWorkbook.Worksheets
WSh.Protect Password:="myPWD", UserInterfaceOnly:=True
DoEvents
If WSh.ProtectionMode = False Then MsgBox "UIFOnly Init Failed on " & WSh.Name & " !!"
End If
Next WSh
End Sub
In some cases the UserInterfaceOnly is not set as expected and I get the "UIFOnly Init Failed on " message at opening "Myfile.xlsm" and as a consequence many other problems later.
EVEN BETTER: I created a new very simple "UnlockUIFOnly.xlsm" file which has the same code in Private Sub Workbook_Open().
If I open "UnlockUIFOnly.xlsm" first, protection works as expected. If I then open "Myfile.xlsm" (keeping "UnlockUIFOnly.xlsm" open) it works as expected.
If I close both files and open ONLY "Myfile.xlsm" it fails again.
I'm running Office 365 (version 2203 Build 16.0.150028.20512) 32 bits with Windows 10.
FURTHER OBSERVATION #1: I copied this not working "MyFile.xlsm" from its original directory to a new one.
When I opened it from its new directory, I got a banner to enable contents, and I answered yes. Then everything went smooth (No UIFOnly Init Failed on " message, no error 1004 ...). I checked some functionalities, so Excel asked whether I wanted to save changes, answered yes, then later if I wanted that document to be a trusted document, answered Yes as well.
At second open, I did not get any banner to enable contents (normal) but the problems were back.
FURTHER OBSERVATION #2: I again copied this not working "MyFile.xlsm" from its original directory to a new one.
When I opened it from its new directory, I got a banner to enable contents, and I answered yes. Then everything went smooth (No UIFOnly Init Failed on " message, no error 1004 ...). I checked some functionalities, so Excel asked whether I wanted to save changes, answered YES, then later if I wanted that document to be a trusted document, answered no. All further open tentatives asked to enable contents (answer yes) but were smooth.
It looks like declaring a document as trusted bypasses something or changes in which order events are generated, and has a huge impact on my problem

Excel (Mac) 2020 version ... Contant Error 400 messages ... any idea why?

I am trying to export a sheet within a workbook as a CSV file. I cannot see any export functions for a sheet. After casting around, it seem that a work around involves creating a new workbook, pasting there and saving that as a CSV.
When I use the .copy method on my sheet, Excel creates a new workbook.
I can access that new workbook in the code below, but the SaveAs line is generating an error 400. I have permissions to write to the folder. Excel simply gives the error message 400. No other indicators. Searching online talks about missing modules (or similar) but mine is a new install and using what I take to be standard methods.
Dim TempWB As Workbook
Dim fileName As String
fileName = ActiveWorkbook.Path & "/theCSV.csv"
Sheets("theCSV").Copy
Set TempWB = ActiveWorkbook
Application.DisplayAlerts = False
TempWB.SaveAs fileName:=fileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
Thanks
#Ken White Thanks for that ... bad coding on my part ...
I changed the variable name and still saw the 400 error messages.
Then I thought, this being MS etc., are they playing lip service again towards Mac compatibility. From my Mac I used an RDS link to a W10 PC running Excel ... no errors!!! These errors seem to relate to code being run on a Mac rather than the via code itself.
Within the RDS, I have a mapped drive directly to my Mac and ran the code using the mapped drive ... i.e. I was writing directly to my Macs folders from Excel in the RDS ... no problems. It does not seem to be an OS permissions thing.
For me, this is a work around, if you have a RDS/VM available.

Constantly getting Err 1004 when trying to using Application.AddIns.Add

I'm trying to implement a bootstrap installer for my add-ins workbook, such that I can easily install the add-in for new users and send out updates. It works fine on my machine, but when having others test it, I get a runtime error when I try to call Set AI = Application.AddIns.Add(fileName:=fullPath, copyfile:=True). Specifically, the error is "1004: Unable to get the Add property of the AddIns class". I thought this was because the user needed to have "Trust access to the VBA project object model" enabled, but the error seems to occur even after they've toggled that box.
Other things I've checked:
The fullPath to the add-in is valid and the user can access the directory and the file
The user has the folder located at Application.UserLibraryPath
Any ideas?
Figured it out. It appears that the issue isn't one of permissions, but rather of whether a workbook is already open. Opening any workbook before running the Addins.Add prevented the error from occurring so I've simply added that into the program:
If Application.Workbooks.Count = 0 then Set wb = Application.Workbooks.Add()
Set AI = Application.AddIns.Add(fileName:=fullPath, copyfile:=True)
If not wb is nothing then wb.Close
Duke, perhaps it's the Trust Center settings on the recipients' machines. I have found this and may be helpful.
Best,
Danny
Check out VBA videos on ExcelVBADude on YouTube.

ODBC Driver has become erratic when making connection and processing SQL query

I have an Excel Macro Workbook (binary extension) that suddenly has developed 2 issues occasionally (sometimes it runs fine).
#1 Issue - Occasionally there is an error on Line 5
It appears the connection does not open. We get the error:
Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x7f8 Thread 0x1174 DBC
#2 Issue - Occasionally there is an error on Line 7
It appears the SQL can not run. It indicates the Worksheet tab can not be found even though it does exist. Note for this error we have no issue with Line 5 (Open Connection). The error that displays is:
[Microsoft][ODBC Excel Driver] The microsoft jet database engine could not find the object 'Worksheet Name'. Make sure the object exists...
For Issue #2 once we close the error dialog box and THE MACRO GETS DELETED !!!
Notes
The code module has not been changed in years Some days we get no errors/issues
This issue occurs for multiple Excel workbooks run by multiple people that run different VBA code blocks. However 1 of the code blocks is the same across all these macros which is the code snippet above.
The source data has not changed in years in terms of formatting or volume.
All these workbooks are on a Network server.
We are on Windows7/Excel 2010/ODBC Excel Driver (xls xlsx xlsm xlsb)
14.00.7180.5000
Code Snippet
1-Set adoConn = Nothing
2-Set adoRS = Nothing
3-Application.EnableCancelKey = xldisabled
4-strConn = "Driver={Microsoft Excel Driver (*.xls,*.xlsx,*.xlsm,*.xlsb)};DriverId=1046;Dbq=" & strFileName & ";IMEX=1;"
5-Set adoConn = New ADODB.Connection: adoConn.Open strConn
6-Application.EnableCancelKey = xlInterrupt
7-Set adoRS = New ADODB.Recordset:adoRS.Open Source:=strSQL,ActiveConnection:=adoConn
I'm curious as to why you're using ODBC to connect Excel to another Excel file, as opposed as to linking the data directly.
Intermittent connection problems point to a network issue. I would suggest removing and re-creating the ODBC connection, but I'd first want to confirm the value of strFileName as referred to in the connection string. Is it an actual server on your internal network, or an external source? (ie, is it a UNC path?)
An intermittent Unable to open registry key error likely sounds worse than it is; when having connection problems, Windows & Excel will easily get confused as to what the real problem is.
It sounds like your setup has been in place, possibly un-maintained, for a long time. When is the last time the client and server were rebooted? (Should be nightly.) Defrag, disk cleanup, etc?
As for the issue of the macro "getting deleted" when you close an error dialog, I'd need to see proof of that. I think you're misunderstanding something, unless you're re-writing the macro from scratch each time this happens..

ExportAsFixedFormat fails sometimes

I have a spreadsheet with forms and macros that worked until recently. The first time I saw the described behavior was the first time I tried using this particular function in Excel 2016 (Windows 10), though I'm not sure that's the cause.
The issue I'm having is with the following line
Worksheets("Label Template - 100X150").ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFilePath, Quality:=xlQualityMinimum, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Which comes from the following macro:
Sub PDFLabelsSheet()
'On Error GoTo errHandler
'enter name and select folder for file
strFile = "Labels_PrintGroup-" & lstPrintGroup.Value _
& "_" _
& Format(Now(), "yyyy-mm-dd\_hhmm") _
& ".pdf"
strFile = ThisWorkbook.Path & "\" & strFile
Worksheets("Label Template - 100X150").Visible = True
UnprotectTab "Label Template - 100X150"
pdfFilePath = Application.GetSaveAsFilename(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If pdfFilePath <> "False" Then
Worksheets("Label Template - 100X150").Select
Worksheets("Label Template - 100X150").Range("A1").Select
Worksheets("Label Template - 100X150").Range("A1").Activate
Cells.Activate
Worksheets("Label Template - 100X150").PageSetup.FirstPageNumber = 1
Worksheets("Label Template - 100X150").ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFilePath, Quality:=xlQualityMinimum, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
exitHandler:
ExecutionEnd
Exit Sub
errHandler:
MsgBox "Something went wrong, a PDF could not be created", vbCritical
Resume exitHandler
End Sub
I've tried permutations of the ExportAsFixedFormat function, changing it to Worksheets("name"), (number), ActiveSheet.... etc.
Prior to executing this particular Sub, the worksheet is unhidden and unprotected. I've tried setting the entire range as PrintArea, I've tried selecting and activating the range to be exported as well.
The most frustrating part is it works sometimes. I've gone as far as putting in code that spits out every property of the PageSetup collection to make sure that something is not blowing things up since the output depends so strictly on the page setup.
When I navigate to this worksheet manually and choose the export function from the file menu, I get the same error. If I click around in that worksheet for a bit the Export function as well as the Macro work.
The PDFLabelSheets Sub does get called from another Sub (invoked by a form's button press) which compiles a boatload of data into this tab, though I've ruled it out as the culprit as successive runs of just the PDF code will succeed then fail without running the other code.
I’ve recently solved a problem that was similar in the following ways:
It involved the failure of the ExportAsFixedFormat, Type:=xlTypePDF
statement
The statement failed with no error message; it simply
stopped the execution of the VBA code
The failure was inconsistent,
and the conditions for failure or success were not obvious
Below is a summary of how I solved it; perhaps this will suggest some useful approaches you can use.
My Excel VBA code was running under Windows 7 as an unattended, end-of-day scheduled task in the background, usually when no one was logged in. Most of the time the code would work, but sometimes it would not. I could not capture the screen after a crash, and capturing the various window contents did not help: there was no useful diagnostic text. I finally tried logging program execution milestones to a disk file, reopening and closing the file for each milestone, so no text would be lost if the program subsequently crashed. That isolated the problem to the ExportAsFixedFormat statement but did not diagnose the problem.
I finally tried having the VBA code save a copy of the workbook just prior to the point of failure. I was hoping that, on re-opening the copy, I’d be able to see what was wrong. That did not help. However, I did notice something strange when comparing the .xlsm files saved on successful and unsuccessful executions – the former were just a little larger.
Digging into the .xlsm files (which are really .zip files), I noticed that, in the xl\printerSettings subfolder, the printerSettings1.bin file was larger after successful runs. Using the SysInternals Strings utility to inspect the .bin files, I found that, in the unsuccessful runs, this file contained only the name of the default printer on the home computer where I had developed the application, which was not the office computer where it was executing. On the successful runs, the .bin file also contained the name of the default printer in the office.
This was the critical difference. In that office, the main computer executes the Excel program shortly after the end of the working day. Ordinarily, during the day this computer prints to a laser printer (set as the default printer) attached to another computer on the network, and that other computer is turned off at the end of the working day. Therefore, depending on accidents of timing, sometimes the end-of-day Excel program would see a valid, available default printer, sometimes not.
Some Excel commands, including the command to save as a .pdf, work properly only when the active printer is valid. There is a similar observation at can't set PageSetup.Orientation = xlLandscape from MS Project, concerning assignments to the fields of .PageSetup. In my case, failing to work properly meant crashing without generating any error message.
I later discovered that my problem was not simply the unavailability of the default laser printer over the network; it was also caused by something irregular about the printer definition. I had added code to log the VBA property Application.ActivePrinter; just prior to a crash, it was returning the value “unknown printer (check your Control Panel)”, rather than containing the name of the printer. When I re-installed the default printer, Application.ActivePrinter always returned the proper printer name, whether or not that printer was available for use, and the program stopped crashing.
My problem was a true Heisenbug – it disappeared whenever I re-ran the Excel workbook at random times. That ultimately turned out to help me confirm its diagnosis. Running unattended, sometimes there was no valid printer. When I logged into my account and ran it attended, either it was during the business day or else LogMeIn temporarily assigned my home printer as a valid default printer. This finally made sense of the fact that the program failed only when it wasn’t being closely observed at the time of execution.
In summary, I’d look at inconsistent printer availability and irregular printer installation as possible underlying causes of failure to consistently export .pdf files using Excel VBA.
Frogrammer-Analyst's analysis is great, but the error is not that ambiguous. You will not have this issue if you login to the server using the user that is running the unattended script. But if you sign out and then try rerunning your script unattended you will see that no printers are mapped and {ExportAsFixedFormat} fails for PDF and or XPS formats.
I have found a solution for my case. A true headeache. Maybe it can help others:
Try uncheking the "PDF/A compliant" option under Options dialog when you export as PDF. After that, run the VBA code again.
For my, it was the solution.
PDF Options

Resources