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.
Related
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?
I am new to VBA coding and hope I can get some assistance here. I am trying to create code that would do the following for ANY cell (without specifying hard coded cell ranges or references):
input a formula in the active cell
copy it (fill) down 10 rows
In an attempt to insert the formula into the ActiveCell I tried:
Sub Test()
ActiveCell.formula = "=IF(ISBLANK(C5)*ISBLANK(D5),"",IF(ISBLANK(D5),(C5),CONCATENATE(C5,"" ["", D5, ""]"")))"
End Sub
However, this produces the
1004: Application-define or object-defined error
I've tried declaring Range objects for ActiveCell but still run into errors.
Any help on this would be highly appreciated.
ActiveCell.formula = "=IF(ISBLANK(C5)*ISBLANK(D5),"""",IF(ISBLANK(D5),(C5),CONCATENATE(C5,"" ["", D5, ""]"")))"
you missed doubling up the first set of embedded quotes.
You can use following routine to copy formula from cell to VBE compatible format. See if it helps you:
Public Sub CopyExcelFormulaInVBAFormat()
Dim strFormula As String
Dim objDataObj As Object
'\Check that single cell is selected!
If Selection.Cells.Count > 1 Then
MsgBox "Select single cell only!", vbCritical
Exit Sub
End If
'Check if we are not on a blank cell!
If Len(ActiveCell.Formula) = 0 Then
MsgBox "No Formula To Copy!", vbCritical
Exit Sub
End If
'Add quotes as required in VBE
strFormula = Chr(34) & Replace(ActiveCell.Formula, Chr(34), Chr(34) & Chr(34)) & Chr(34)
'This is ClsID of MSFORMS Data Object
Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
objDataObj.SetText strFormula, 1
objDataObj.PutInClipboard
MsgBox "VBA Format formula copied to Clipboard!", vbInformation
Set objDataObj = Nothing
End Sub
After inserting this routine. You just need to enter the formula normally in the cell. Then stay on the cell and run this code and it will copy to clipboard. Go to VBE and do CTRL+V to paste the code where required.
Originally posted on:
https://chandoo.org/forum/threads/copy-formula-from-excel-to-clipboard-in-vba-compatible-format.35997/
I am trying to replace on the line Application.Run "c:\users\navin\test\" with path but it won't work. (Error 1004).
Sub test()
Dim path As String
path = "c:\users\navin\test\"
Workbooks.Open (path & "excel.xlsb")
Application.Run "'c:\users\navin\test\new.xlsb!macro1'"
Workbooks("excel.xlsb").Close SaveChanges:=True
End Sub
Currently you open a workbook called excel.xlsb and then attempt to run a macro in a workbook called new.xslb. You also have two sets of quotes, which is likely to cause problems.
Where you attempt to run the macro, you should reference only the name of the workbook.
Application.Run "excel.xlsb!macro1"
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.
I have created a simple worksheet macro that sends the contents of a cell to an external program when the cell is double clicked. At first, I had all of the code in the sheet module, and had to copy it to each sheet on which I wanted the functionality. Now, I managed to reduce the code in the sheet module to a call to a subroutine in a standard module and it works, but I stil have to copy the code to each sheet on which I need the functionality. Is there a way to enter the code in only one place (a standard module, workbook module or class module) and have it function on any sheet in the workbook without code behind the sheet? Thank you for your help.
The ThisWorkbook code module has a Workbook_SheetBeforeDoubleClick event handler which you can use instead of capturing the event separately on each sheet.
You need an event handler on the sheet to take care of the double-click. Put this in the code behind each sheet you want to run the double-click code.
Option Explicit
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim sWorksheet As String
Dim sValue As String
Dim sCell As String
sWorksheet = ActiveSheet.Name
sValue = Target.Text
sCell = Target.Address
Call DoubleClicked(sWorksheet, sValue, sCell)
End Sub
Put your main routine in a module, and not on the sheet.
Option Explicit
Sub DoubleClicked(SheetName As String, CellText As String, CellAddress As String)
' your code goes here
MsgBox "You double-clicked cell " & CellAddress & " on sheet " _
& SheetName & ". The text in that cell is: " & CellText
End Sub
You don't want the logic repeated on each sheet. If you make a change, you have to change it for every single sheet. By simply calling the main routine from each sheet, you only have to write and maintain it once.