Excel 2010 - Error: Cannot run the macro SelectCell using .onAction - vba

I have been looking all over the internet for a solution to this problem but for some reason I can never find anything directly related to using .onAction with selecting a specific cell.
I am using an answer to another question as a reference:
https://stackoverflow.com/a/18199035
In the section where it is looping through shapes, the script assigns an .onAction event to each shape. Whenever this is run in Excel 2010 I get the error:
Cannot run the macro "SelectCell "Sheet 1","$C$10"".
The macro may not be available in this workbook or all macros may be disabled.
I am new to VBA scripting for excel so I have no idea if it is the formatting, but I know it is related to this line.
.OnAction = "'SelectCell """ & ws.Name & """,""" & cll.Address & """'"
I created a sub-procedure for SelectCell to display the values being sent as a debug. Same error.
I tried having excel allow all macros and disable all macros but it had no effect on the error.
If anyone has any idea of where I am going wrong or any resources I can use to further educate myself, it would be greatly appreciated.

This (both subs in a regular module) works for me.
Sub SelectCell(sht As String, rng As String)
ThisWorkbook.Sheets(sht).Range(rng).Select
End Sub
Sub Assign()
ActiveSheet.Shapes(1).OnAction = "'SelectCell """ & _
Selection.Parent.Name & """, """ & _
Selection.Address() & """'"
End Sub
If SelectCell is in a sheet code module, then you need to include the sheet code name:
Sub Assign()
ActiveSheet.Shapes(1).OnAction = "'Sheet1.SelectCell """ & _
Selection.Parent.Name & """, """ & _
Selection.Address() & """'"
End Sub

If I'm reading this right, "SelectCell" is a macro name, and you're passing in "Sheet 1","$C$10" as parameters (as strings). Whenever you make a call on the right side of an assignment operator (equals sign) the parameters need to be passed in with parenthases. for example,
.OnAction = "SelectCell "Sheet 1","$C$10""
is wrong, and
.OnAction = "SelectCell ("Sheet 1","$C$10")"
is right.
Try that, but there's not much I can go off without much code. You could also try to use the fully qualified macro name, in case the Macro is in another module.

Related

Run-time error VBA upon changing ":" to ";"

Im trying to dynamically add a formula in an Excel sheet using VBA. Something really odd happens. When dynamically creating a formula by using "&" to link together the various components of a string, its gives a Run-time error '1004': Application-defined or object defined error.
This is working (but produces the wrong formula):
Worksheets("Sheet1").Cells(row, 7).Value = "=BDP(f" & row & ":Security Name)"
This is not working (produces the above mentioned error):
Worksheets("Sheet1").Cells(row, 7).Value = "=BDP(f" & row & ";Security Name)"
Note that the ONLY difference is the ":" in front of Security Name became a ";".
Any idea why this is producing this error?
Also, "Security Name" should also be between quotation marks, but when I double up the quotation marks, or use & Chr(34) I get the same error again.
What I am looking for is a formula to be added to the cell which looks like this =BDP(F4:"Security Name")
Your help is appreciated!
If you want a ; in the actual formula you need to use a , in the String you are using.
Also If you write this "" inside the string it will result in this in your string "
So this in you VBA:
.Formula = "=BDP(f" & Row & ",""Security Name"")"
will result in this in you actual cell:
=BDP(F5;"Security Name") (For me the Row was 5)
(You also can set the .Value property instead, but since you´re setting a formula i´d suggest using the .Formula)
Edit:
The method I used, mentioned in the comments:
Sub test()
BBCode = "XS0357495513 Corp"
Sheets(1).Range("A1").Formula = "=BDP(""" & BBCode & """,""Security Name"")"
'Range("A1") is like Cells(1, 1)
End Sub

Inserting code into new worksheet with CodeModule requires VB editor to be open

I'd like to be able to add code to a newly created worksheet. The following block of code does that, but will give me an error (pointing to the first line of the code below) if the Visual Basic editor is not open. And, if it is open in the background, it will activate the VB editor window after the macro finishes running.
With wb.VBProject.VBComponents(wb.Worksheets(newSheetName).CodeName).CodeModule
.InsertLines Line:=.CreateEventProc("FollowHyperlink", "Worksheet") + 1, _
String:=vbCrLf & _
"Call FindAllInSheet(Target.Range.Text, Range(Cells(2, 2),Cells(" & num_triple_combos + 1 & ", " & start_triples_col + 1 & ")))"
End With
Is there a way to avoid this behavior?
For now, what I've done that works is by surrounding my code with
Application.VBE.MainWindow.Visible = True
...
Application.VBE.MainWindow.Visible = False
The only issue now is that the macro will cycle through every single existing sheet before adding the code to the designated sheet. I'm not sure why.
Source for my lead: http://www.mrexcel.com/forum/excel-questions/31259-macro-call-visual-basic-editor.html

Selection.OnAction = "Workbookname!Macroname"

Say you have two Workbooks one called “MyWorkbook” and the other called “PatchMyWorkbook”. Both workbooks are open at the save time. The “PatchMyWorkbook” has a macro to add a button and assign an existing macro of “MyWorkbook” to “MyWorkbook” The existing macro in “MyWorkbook” is called “PrintPage”
Windows(“MyWorkbook”).Activate
Sheets("Sheet1").Activate
ActiveSheet.Buttons.Add(665.25, 43.5, 89.25, 45).Select
Selection.OnAction = "PrintPage"
This does not cause an error while the “PatchMyWorkbook” code executes but the newly added buttons macro will point to “’PatchMyWorkbook’!PrintPage” rather than just “PrintPage” of the “MyWorkbook”
Question: How can you set the “OnAction” for a macro button across workbooks so that the macro will point to the current workbook not the workbook from where the macro has been created?
In my opinion .OnAction property should be set in this way:
Selection.OnAction = myWbk.Name & "!PrintPage"
By the way, the idea from your comment (changed a bit below):
Selection.OnAction = "'" & myWbk.Name & "'" & "!" & "PrintPage"
is working for me as well (Excel 2010).
You need to include the name of the sheet or module where PrintPage is defined.
Dim methodName As String
With <module or sheet where 'PrintPage' is defined>
methodName = "'" & MyWbk.Name & "'!" & .CodeName & ".PrintPage"
End With
MyWbk.Sheets("Sheet1").Shapes("ButtonName").OnAction = methodName
The single quotes surrounding MyWbk.Name are important.
A quick and easy way is :
workbooks("name_of_workbook").Worksheets("name_of_sheet").Shapes("name_of_button").OnAction = "name_of_your_macro"
Just substitute the different "name_of_..." by your names.
Does it work?

Error Handling on external Macro

I am just wondering if it would be possible to do error handling on an external macro. Basically what I want to achieve is I have have thousands of excel workbooks that come in daily and I want to open each of them and run the macro from them (easily done just use the Application.run feature )
Application.Run ("'" & ActiveWorkbook & "'!Export")
What I want to achieve is I want to run error resolving function if that external macro incurs an error.
This is what I have so far
Dim str_SearchFile, str_FileName, str_SearchPath As String
Dim wb_WorkBook As Workbook
Application.ScreenUpdating = False
Application.DisplayAlerts = False
str_ThisBook = ActiveWorkbook.Name 'Set the current workbook for later reference
str_SearchPath = Sheets("Control Panel").Range("E2")
str_SearchFile = Sheets("Control Panel").Range("E2") & "\*.xls*" 'Sets the file type to search for
str_NextFile = Dir(str_SearchFile, vbDirectory) 'Sets the amount of files in the directory matching the criterea (.xls)
Do While Len(str_NextFile) > 0
On Error Resume Next
Set wb_WorkBook = Workbooks.Open(Filename:=str_SearchPath & "\" & str_NextFile, Password:="")
If Err.Number = 0 Then
On Error GoTo 0
Application.Run ("'" & str_NextFile & "'!Export")
str_FileName = str_SearchPath & "\Done" & "\" & str_NextFile
wb_WorkBook.Save
wb_WorkBook.Close
FileCopy (str_SearchPath & "\" & str_NextFile), str_FileName
Kill (str_SearchPath & "\" & str_NextFile)
End If
str_NextFile = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Any Advise is very welcome!
Thank you in advance
You won't be able to get this to work the way you are trying.
The MSDN on On Error Statement indicates that it (emphasis added):
Enables an error-handling routine and specifies the location of the
routine within a procedure; can also be used to disable an
error-handling routine.
The VBE Glossary defines a procedure as:
A named sequence of statements executed as a unit. For example,
Function, Property, and Sub are types of procedures. A procedure name
is always defined at module level. All executable code must be
contained in a procedure. Procedures can't be nested within other
procedures.
This means that calling error handling before calling the macro in the other book, will be ignored in the called macro (confirmed through testing).
The only way that you would be able to enable error handling would be to actually modify the code in the workbook prior to calling the macro... which is very complicated. For your reference, here is a webpage giving an example of editing project code from VBA.
The easiest way I would deal with this is to change your external workbook's "Export" sub into a function that returns a value - Say an integer.
What you can then do is put error trapping into that function and, based upon the outcome of the procedure it can return, say:
0 = All Went Well
1 = Failed to do XXX
2 = Failed to do YYY
You could then change your code to something like this:
Select Case Application.Run ("'" & str_NextFile & "'!Export")
Case 0
MsgBox "All Went Well"
Case 1
MsgBox "Failed to do XXX"
Case 2
MsgBox "Failed to do YYY"
End Select
This will allow you to put the error trapping where it belongs and know how the procedure ran.
hope this helps

How to assign a hyperlink and an onaction event to a shapes object in Excel

In microsoft excel vba, I am attempting to assign hyperlinks and/or actions to shapes I have drawn. Here is roughly what I have tried (uncomment only one line at a time)
Basically, what I want to do is allow users to get more information by clicking on a shape object. Hyperlinks are fine, but some kind of event handler which accepts parameters would be ideal. I will be creating hundreds of these shapes, and they need to link to unique places in the document.
Dim destinationHyperlinkCell as Range
set destinationHyperlinkCell = Range("10:10")
' (do some stuff here)...
With Sheet1.Shapes.AddTextbox(msoTextOrientationHorizontal, _
600, _
600, _
300, _
16)
.TextFrame.Characters.Text = "Test this thing"
.Name = destinationHyperlinkCell.Address & " group of shapes"
'.Hyperlink.Address = destinationHyperlinkCell.Address
'.Hyperlink.Range = destinationHyperlinkCell.Address
'.OnAction = "'showDebugMsg """ & .Name & """'"
End With
use "Assign Macro ..." to define a macro to each shape which fires on "Click"
You can use the same macro for each shape and use the Application.Caller property to get the name of the shape which fired the macro. Then you have all the ingredients to write an intelligent handler - like a (hidden) Excel table that resolves shape name into an URL, text or whatever
Sub Shape_Click()
MsgBox "Co-Cooo! from" & Application.Caller
End Sub
Hope that helps
Good luck - MikeD