Home > Software engineering >  Programmatically click a button in Excel through Macro (VBA)
Programmatically click a button in Excel through Macro (VBA)

Time:12-02

I have a custom-button, linked to a macro which does a few things. After they are done, I want the code to programmatically click the below highlighted button (more clearly, open the import XML dialog), so my user could see the file selection window and it would proceed for it's further tasks.

Representative image

enter image description here

Here's my current macro code:

Option Explicit

Sub Button1_Click()
    ' ... All my existing macro code
    
    ' ---------- programmatically click the Import button (from Developer) here ------------
End Sub

What should I add in my macro to achieve this?

CodePudding user response:

I have found the solution to my question -

% - Alt
l - Developer
t - Import

are the shortcut keys to import an XML into the sheet, and this command runs the shortcut keys programmatically, opening my desired file selection box. -

Application.SendKeys ("%lt")

CodePudding user response:

CommandBars.ExecuteMso method:
https://docs.microsoft.com/en-us/office/vba/api/Office.CommandBars.ExecuteMso

"Executes the control identified by the idMso parameter."
Hover over the button where you would add it to the ribbon, you will see the text includes "XmlImport"

"This method is useful in cases where there is no object model for a particular command. Works on controls that are built-in buttons, toggleButtons, and splitButtons."

Private Sub ExecuteMso_MoveToFolder()
    ' https://docs.microsoft.com/en-us/office/vba/api/Office.CommandBars.ExecuteMso
    ' Hover over the button where you would add it to the ribbon,
    '  you will see the text includes "XmlImport"

    CommandBars.ExecuteMso ("XmlImport")
End Sub
  • Related