Run-time error 1004 - couldn't find BloombergUI - vba

I'm running a batch file that executes a VBScript that runs a macro in an Excel sheet on Bloomberg Terminal.
The excel sheet contains a lot of BDP formulas in cells. These all work fine. Initially, I a had a problem updating the data from Bloomberg and running the macro but this was solved by using bloombergui.xla.RefreshAllStaticData + a timer.
The macro runs perfectly when executed manually in excel but I am getting a "run-time error 1004 couldn't find bloombergui.xla..." when trying to automate it via batch & VBS.
Any ideas how to solve this? I think I have exhausted all options via google.
Macro:
Sub UpdateWeekly()
Application.Run "bloombergUI.xla!RefreshAllStaticData"
Application.OnTime (Now + TimeValue("00:00:25")), "WeeklyPDF"
End Sub
Sub WeeklyPDF()
Application.ScreenUpdating = True
ActiveSheet.Range("A1:V225").Select
Selection.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="O:\LOCATION" & Format(Date, "MMMM-DD-YYYY") & " " & "Weekly", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Application.PrintCommunication = False
End Sub
VBScript:
Dim args, objExcel
Set args = WScript.Arguments
Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open args(0)
objExcel.Visible = True
objExcel.Run "UpdateCreditWeekly"
objExcel.ActiveWorkbook.Close(0)
objExcel.Quit

Bloomberg Add-in fails to load when Excel is instantiated programmatically ... I think you need to load it again every time.
Ensure the AddIn is there before calling Application.Run "bloombergUI.xla!RefreshAllStaticData"
Sub UpdateWeekly()
Dim blpAddin As Workbook
On Error Resume Next
Set blpAddin = Workbooks("bloombergUI.xla")
On Error GoTo 0
If Not blpAddin Is Nothing Then ' Check if add-in is loaded or not
Application.Run "bloombergUI.xla!RefreshAllStaticData" ' refresh Bloomberg formulas
Application.OnTime (Now + TimeValue("00:00:25")), "WeeklyPDF" ' wait till bloomberg Formulas calculation complete
Else
Debug.Print "Bloomberg Add-in is not loaded"
End If
End Sub
If Add-in is not there then you need to Add/load add-in
'To load the Add-in
Application.Addins.Add(file path & name)
OR
AddIns("Add-In Name").Installed = True

I believe your syntax is incorrect.
Application.Run can be used to run a macro written in Visual Basic or
the Microsoft Excel macro language, or to run a function in a DLL or
XLL.
The macro you specify can be either a string with the macro name,
or a Range object indicating where the function is, or a
register ID for a registered DLL (XLL) function. If a string is
used, the string will be evaluated in the context of the active sheet.
Also, if you're using a newer version of Excel you're going to have further problems because I believe XLA is an older filetype, since replaced by XLAM.
See the links below for more information, especially this one and this one.
More Info:
MSDN: Application.Run method (Excel)
Ron de Bruin : How do I use Application.Run in Excel
Stack Overflow : Run Excel Macro from Outside Excel Using VBScript From Command Line
Stack Overflow : How do I call an xll addin function from vba?

Related

How to save a WorkSheet from an Excel spreadsheet as a PDF

I'm trying to write (what I thought would be) a simple macro which will save a Worksheet (not the whole Workbook) from an Excel Spreadsheet as a PDF. I'm using Excel 2016 (15.24) on a MacBook Pro running Yosemite. I've seen lots of examples here and online.
I started out by recording a macro and edited it. It looked like this:
Sub SavePDF()
ActiveWorkbook.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF, _
PublishOption:=xlSheet
End Sub
This produced a PDF file but it contained all of the sheets from the Workbook. It seems that, for some reason, the PublishOption:=xlSheet although it works manually when recording the macro, does not work from VBA.
Ok. So I tried a different approach using ExportAsFixedFormat, modelling my approach on some of the examples I've seen here and elsewhere online and trying to keep it as simple as possible. Here's my version.
Sub SimplePDF()
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="pdfs/example.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Every time I try this I get a print error, followed by the dreaded run-time error 1004. BTW, does anyone know the definition of this error?
Can anyone suggest why this is not working? I'd be grateful for any advice.
On the strength of Sinan's advice below I changed the code to
Sub SavePDF()
ActiveSheet.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF
End Sub
I get the same run-time error 1004 but it gives me the extra information "SaveAs method of Worksheet class failed"
I tried David Zemens technique below of copying the active worksheet to a new Workbook and then using SaveAs on that new workbook.
Sub NSavePDF()
ActiveSheet.Copy
ActiveWorkbook.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF, _
PublishOption:=xlSheet
'Close the new workbook without saving it.
ActiveWorkbook.Close False
End Sub
However, this attempts to print the worksheet on my default printer rather than converting to PDF.
You are asking to save the entire workbook and that is what is happening. Instead, you can figure out which worksheet you want to save as PDF, and invoke SaveAs method on that.
See Worksheet.SaveAs instead of Workbook.SaveAs.
Saves changes to the chart or worksheet in a different file.
Syntax
expression.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AddToMru, TextCodepage, TextVisualLayout, Local)
expression: A variable that represents a Worksheet object.
Sub SaveSheetAsPDF()
ActiveWorksheet.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF
End Sub
If some reason that doesn't work (but Workbook.SaveAs does), you could simply copy the sheet to a new workbook containing only one sheet, and then do SaveAs on that workbook.
Sub SavePDF()
ActiveSheet.Copy '## This creates a new workbook containing only the copied sheet
'ActiveWorkbook should now be the new/copied worksheet:
ActiveWorkbook.SaveAs Filename:= _
"pdfs/excelsheetstopdf.pdf", FileFormat:=xlPDF, _
PublishOption:=xlSheet
'Close the new workbook without saving it.
ActiveWorkbook.Close False
End Sub

Using Application.Run to open a workbook with protected worksheets and protected VBAProject

An employee at one of my company's local offices is working on a macro in Sheet1 of a workbook that would run a macro in another workbook using Application.Run:
Private Sub CommandButton1_Click()
Wfile = Range("B2").Value
Wpath = Range("B3").Value
Workbooks.Open Wpath + "/" + Wfile
Application.Run Wfile & "!copy_rates_macro"
End Sub
The workbook that he is trying to open/use is protected in every way possible (all of its sheets are protected and its VBAProject is protected as well.
When the macro is run, the 1004 run-time error message window pops up saying "Cannot rund the macro 'Name.xlsm!copy_rates_macro'. The macro may not be available in this workbook or all macros may be disabled.'
I did a lot of research and I thought the putting the following in the protected file would work:
Private Sub Workbook_Open()
' Dim wSheet As Worksheet
' For Each wSheet In Worksheets
' wSheet.Protect Password:="pw", UserInterFaceOnly:=True
' Next wSheet
Application.EnableEvents = False
End Sub
Note that the parts commented out above are my additions to code that was already there and must remain there. Also, "pw" is the password for every worksheet and the VBAProject.
This code didn't make a difference (it wasn't commented out when I ran it), and I imagine it has something to do with the VBAProject being protected.
Is this request even possible, or is it a lost cause? My boss doesn't want the password to the protected workbook to be released but I can't see a way around it.
Thanks for any help.
You shouldn't have to unprotect a project to run code in it (that would make it pretty worthless), but I can see a couple of possible issues in your code. First you use "/" at the end of the path rather than "\" and second, if the workbook name contains spaces you need to enclose it in single quotes:
Workbooks.Open Wpath + "\" + Wfile
Application.Run "'" & Wfile & "'!copy_rates_macro"
If that still won't run, there are a few possible pitfalls:
1. The macro is in a module of the same name, or in an object module, such as a worksheet or ThisWorkbook, in which case you need to prefix the macro name with the code name of the object.
2. Automation Security may be disabling macros in the opened workbook. To work around that, try adding:
Application.AutomationSecurity = msoAutomationSecurityLow
before opening the workbook. Ideally, you should store the current value and reset that at the end.

application.run vba not working with sheet macros

My file has different sheets with the same-named sub routine inside each doing different things specific to the sheet. So, I'm trying to call dynamically a macro inside a selected sheet using Application.Run from a module. All sheets' "object" name (I don't know how to call those) are already modified to be the same as its view (inside the bracket) name, without the spaces.
macro = Chr(39) & ThisWorkbook.Name & Chr(39) & "!" & Replace(SheetName, " ", "") & "." & "Harmoniser()"
Application.Run macro
Here's an example of the Harmoniser macro in a Sheet.
Sub Harmoniser()
ActiveSheet.Range("k22").GoalSeek Goal:=0, ChangingCell:=Range("l13")
MsgBox ("Done!")
End Sub
Somehow, only the MsgBox works, and it shows it twice everytime. Debugging by putting a break point doesn't work either. It happens to all of my sheets. Is there a limitation to Application.Run that it only allows certain code or there's an error that Excel is not giving me?
I get the same thing when I run your code. I tried a few different tweaks and am able to enter debug/breakpoint mode if I do this:
Sub t()
Dim sht As Worksheet
Dim macro As String
For Each sht In ThisWorkbook.Worksheets
sht.Activate
macro = sht.CodeName & ".Harmoniser"
Application.Run macro
Next
End Sub
Your code may have been erroring silently because you were using ActiveSheet without first Activating the sheet which contains the macro to be run. Not sure about the double-display of the MsgBox, but seems like that may be related.

Macro runs only once

I have a "master" timesheet macro which users open and complete. Upon close I force a macro (in ThisWorkbook) to run and rename the master to a filename held in range save name.
This works perfectly the first time the user opens Excel, edits and closes the workbook. However, if the user opens "master" timesheet the second time, completes another timesheet and closes, without closing Excel in between, then the macro does not run.
I have searched extensively to see if there is some "global variable" that I need to reset but with no joy.
Here is the code. Any advice would be appreciated.
Private Sub Workbook_BeforeClose(SaveAsUI As Boolean)
If Not SaveAsUI Then
Cancel = True
Application.EnableEvents = False
MSG1 = MsgBox("This File will be saved as....... " & Sheets("Timesheet").Range("savename").Value & ".xlsm", vbOKOnly, "Confirm")
Me.SaveAs Filename:=ThisWorkbook.Path & "\" & Sheets("Timesheet").Range("savename").Value & ".xlsm"
ActiveWorkbook.Close False
Application.EnableEvents = True
End If
End Sub
#Bob, seems as if this has something to do with the BeforeClose event. Before closing the workbook, you're trying a SaveAs. This could cause some issues. Did you try to debug this macro? If yes, what did you found?

How to run a macro only if the Excel workbook is open with VBScript?

World!
I am trying to automate a report task at my job and I have the following situation:
I need to execute a macro on a workbook by using a script. I tried to write a vbscript to do the job, and this is the significant part of it:
Set objWbk = GetObject("***Path***\test.xlsm")
objWbk.Application.Run "test.xlsm!test"
WScript.Quit
The macro runs perfectly. My real problem is that I only want to do the report only if the workbook is open.
Is there a way (in vbs or vba) to determine if that workbook is open ? (by the way, it is located on another computer on my network)
Since you want to run the macro only when the workbook is already opened, something like this might work:
wbName = "test.xlsm"
wbFullName = "***Path***\" & wbName
Set xl = GetObject(, "Excel.Application")
For Each wb In xl.Workbooks
If LCase(wb.Path & "\" & wb.Name) = wbFullName Then
wb.Application.Run wbName & "!test"
End If
Next
This is not fully tested and may a need a bit of modification but see if it gets you what you need.
On Error Resume Next
Set objWbk = GetObject("***Path***\test.xlsm")
If Err.Number = 0 Then objWbk.Application.Run "test.xlsm!test"
wScript.Quit