473,592 Members | 2,921 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Access VBA to run Macro when an excel toolbar button is clicked

126 New Member
Hello everyone, the following is the code which opens an excel file and creates a toolbar button.
And, when I click the toolbar button as shown at line #28, the code should call the "Example" macro. But, it is displaying "The Macro "Example" cannot be found" Message Box.

Can anyone suggest an idea on how to call the macro whenever a user clicks the toolbar button?

Your help will be much appreciated. Thanks!

Expand|Select|Wrap|Line Numbers
  1. Sub RunMacro1()
  2. Dim xlApp As Excel.Application
  3. Dim xlWB As Excel.Workbook
  4. Dim xlWS As Excel.Worksheet
  5. Dim myCB As CommandBar
  6. Dim myCBtn1 As CommandBarButton
  7.  
  8. Set xlApp = New Excel.Application
  9. xlApp.Visible = True
  10. xlApp.Interactive = True
  11. Set xlWB = xlApp.Workbooks.Open("C:\ExtractPolicyList1.xls", , False)
  12. Set xlWS = xlWB.Worksheets("SelectPolicies")
  13.  
  14. With xlApp
  15. ' Delete the commandbar if it exists already
  16. On Error Resume Next
  17. .CommandBars("example").Delete
  18. ' Create a new Command Bar
  19. Set myCB = .CommandBars.Add(Name:="example", _
  20.             temporary:=True, Position:=msoBarTop)
  21.  
  22. ' Add button 1 to this bar
  23. Set myCBtn1 = myCB.Controls.Add(Type:=msoControlButton)
  24. With myCBtn1
  25.     .Caption = "Example"
  26.     .Style = msoButtonIconAndCaption  '<- will force the caption text to show on your button
  27.     .FaceId = 1952
  28.     .OnAction = "Example"
  29. End With
  30. ' Show the command bar
  31. myCB.Visible = True
  32. End With
  33. Set xlApp = Nothing
  34. End Sub
Expand|Select|Wrap|Line Numbers
  1. Sub Example()
  2. MsgBox "it works!"
  3. End Sub
Aug 1 '08 #1
3 7655
Stewart Ross
2,545 Recognized Expert Moderator Specialist
Hi again JFKjr. I have tested your command bar code along with a test message box outputting a "hello world" and it works fine for me.

For sub Example to be called by the command button it must be located in a public code module within the worksheet (in my case in the default Module1) - could you confirm that it is? The Excel worksheet will not be able to access the sub if it is really located in the Access VBA code, or if it is associated with a private code module in the worksheet (e.g. those associated with individual worksheets).

While researching this one I came across a page by the multitalented Dev Ashish (page linked here) which shows how to call an Excel worksheet function from automation code such as code running in Access, using the .Run method of the application object

xlapp.run ("name of sub or function")

I've tried this out on a "Hello World" example message box and it works fine too, but it is not linked to the command button in Excel so is not the solution to what you asked. Anyway, it is interesting so I mention it here for future reference. You may already know of it from your previous marathon thread on Excel/Access interaction.

-Stewart
Aug 3 '08 #2
JFKJr
126 New Member
Hi again JFKjr. I have tested your command bar code along with a test message box outputting a "hello world" and it works fine for me.

For sub Example to be called by the command button it must be located in a public code module within the worksheet (in my case in the default Module1) - could you confirm that it is? The Excel worksheet will not be able to access the sub if it is really located in the Access VBA code, or if it is associated with a private code module in the worksheet (e.g. those associated with individual worksheets).

While researching this one I came across a page by the multitalented Dev Ashish (page linked here) which shows how to call an Excel worksheet function from automation code such as code running in Access, using the .Run method of the application object

xlapp.run ("name of sub or function")

I've tried this out on a "Hello World" example message box and it works fine too, but it is not linked to the command button in Excel so is not the solution to what you asked. Anyway, it is interesting so I mention it here for future reference. You may already know of it from your previous marathon thread on Excel/Access interaction.

-Stewart
Hello Stewart, nice to see you again :). Thanks for your reply.

Yes, you are right, I am able to run the "Example" sub above if I place the sub in a worsheet code module which has toolbar button. But I do not want to manually place the proc/sub in the worksheet. I would like to do it programmaticall y.
(FYI: The link from your post shows how to run an excel macro, which is already created in excel, through access VBA)

This is what I am looking for, well I am considering two cases and like to use whichever alternative is possible:

I am able to open an excel file and create a toolbar button through Access VBA, keeping that in mind, I would like know if the following alternatives are possible:

a) call a proc/sub defined in access VBA whenever a user clicks the excel toolbar button.

b) the following code (line #37 to 46) is used to create a sub in worksheet code module through Access VBA and the sub is called whenever a user clicks the excel toolbar button.

But it is only possible if the user checks/selects "Trust access to the VBA project object module" macro security option of the excel file.

Expand|Select|Wrap|Line Numbers
  1. Sub RunMacro1()
  2. Dim xlApp As Excel.Application
  3. Dim xlWB As Excel.Workbook
  4. Dim xlWS As Excel.Worksheet
  5. Dim myCB As CommandBar
  6. Dim myCBtn1 As CommandBarButton
  7. Dim vbp As Object
  8. Dim newmod As Object
  9. Dim StartLine As Long
  10. Dim cLines As Long
  11.  
  12. Set xlApp = New Excel.Application
  13. xlApp.Visible = True
  14. xlApp.Interactive = True
  15. Set xlWB = xlApp.Workbooks.Open("C:\Book1.xls", , False)
  16. Set xlWS = xlWB.Worksheets("Example")
  17.  
  18. With xlApp
  19. ' Delete the commandbar if it exists already
  20. On Error Resume Next
  21. .CommandBars("example").Delete
  22. ' Create a new Command Bar
  23. Set myCB = .CommandBars.Add(Name:="example", _
  24.             temporary:=True, Position:=msoBarTop)
  25.  
  26. ' Add button 1 to this bar
  27. Set myCBtn1 = myCB.Controls.Add(Type:=msoControlButton)
  28. With myCBtn1
  29.     .Caption = "Example"
  30.     .Style = msoButtonIconAndCaption  '<- will force the caption text to show on your button
  31.     .FaceId = 1952
  32.     .OnAction = "Example"
  33. End With
  34. ' Show the command bar
  35. myCB.Visible = True
  36. End With
  37. Set vbp = xlWB.VBProject
  38. Set newmod = vbp.VBComponents.Add(1)
  39.  
  40. With xlWB.VBProject.VBComponents("Module1").CodeModule
  41.     cLines = .CountOfLines + 1
  42.     .InsertLines cLines, _
  43.         "Sub Example()" & Chr(13) & _
  44.         " Msgbox ""Eureka, it works!""" & Chr(13) & _
  45.         "End Sub"
  46. End With
  47. Set xlApp = Nothing
  48. End Sub
Is it possible to create a sub in worksheet code module without asking the user to check/select "Trust access" macro security option?

Feel free to suggest any other alternative solutions to my problem.

Hope I did not confuse you!
Aug 3 '08 #3
NeoPa
32,566 Recognized Expert Moderator MVP
If you are setting the .OnAction value to the name of your procedure from a foreign application (Access for instance), I think you may need to specify a module qualifier.
For instance your line #32 (in post #3) should be changed to something like :
Expand|Select|Wrap|Line Numbers
  1. .OnAction = "Module1.Example"
If the case is even more extreme then it may need a filename qualifier. The format of that, assuming the spreadsheet is named something like "C:\Program Files\Test\Proj ect.Xls" would be :
Expand|Select|Wrap|Line Numbers
  1. .OnAction = "'C:\Program Files\Test\Project.Xls'!Module1.Example"
Aug 10 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

2
10782
by: Rich Anton | last post by:
I am a newbie to Access. I have used Lotus Approach much over the years, but not Access. What I am trying to do is to create an opening screen with a bar menu that will basically allow me to select what I want to do, whether it be to generate a specific report or enter data to a specific form or run a specific macro. It would be great if this screen would act as the main interface screen, and that after closing the selected form,...
6
4731
by: Peter Frost | last post by:
Please help I don't know if this is possible but what I would really like to do is to use On Error Goto to capture the code that is being executed when an error occurs. Any help would be much appreciated. Thanks in advance
1
3695
by: Bon | last post by:
Hello all I create a form with three buttons in MS Access 2000. They are Open Excel Template, Save Draft and Save Final. When I click the Open Excel Template button, the Excel template will be opened. Inside the Excel template, I have assigned a draft watermark to the Print icon. When the Print icon is clicked, the draft watermark and print dialog box is shown. After the user print/edit data in the Excel template, s/he has to click
3
1917
by: Deb | last post by:
I am doing something wrong, but I don't know what! I converted some of my macros to modules -- but they won't run. I debugged/compiled but the run command still is greyed out. What do I need to change. I know that this is a basic question, but I am very new to code and need all the help I can get.
37
5202
by: jasmith | last post by:
How will Access fair in a year? Two years? .... The new version of Access seems to service non programmers as a wizard interface to quickly create databases via a fancy wizard. Furthermore, why would you even continue to use Access as a backend when you have a much superior option in SQL express? What about as a future front-end development tool? Let's get serious. Microsoft continues to publish numerous articles and videos on how you...
1
5726
by: garry.oxnard | last post by:
Can anyone help me to solve a problem which involves switching from Access to Excel (then back to Access) programatically please? I have an Excel template which, on open, also opens an Access database - containing a list of addresses. Sequence of events is = (1) Excel template opens in its default XXX.xls filename. (2) Code runs to save the spreadsheet as XXX.xls. (3) User clicks a button to open an Access database containing an
2
1826
by: bandkindy | last post by:
To preface, I am pretty green on the whole sql thing, but am learning quickly so please bear with me. I have an excel file that is copied to 5 users directories so they have their own working copy. This file is populated by the user. There is a macro that saves the file and names it based on specific data the user enters (first last name). I have that working fine. I also have created a macro that dumps the data to an Access 2007 db named...
1
1532
by: bandkindy | last post by:
To preface, I am pretty green on the whole sql thing, but am learning quickly so please bear with me. I have an excel file that is copied to 5 users directories so they have their own working copy. This file is populated by the user. There is a macro that saves the file and names it based on specific data the user enters (first last name). I have that working fine. I also have created a macro that dumps the data to an Access 2007 db named...
16
5163
by: Phil Stanton | last post by:
I have a form with a button which is supposed to open an Excel file (With lots of Macros /VBA) in it. The Excel file gets it's data from the Access program Here is the code Private Sub Storage_Click() On Error GoTo Err_Storage_Click
0
7871
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7995
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8227
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6642
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5400
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2379
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1467
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.