Add custom menu option in mouse right click event - vba

When some words is selected in the document and right click, macro function should be called. Or something like, custom right click menu option should be added and when I click that menu option, macro should be called.
For example:
In the document I have four digit numbers like 2001 and 2010. When I select four digit number and hit right click and press my custom menu option, macro should be called and selected four digit no. should be parsed to the macro function which is called.
I got some code but its for Excel, I dont't know how to customize it for Microsoft Word.
Code for excel:
Const strMacro = "YourCode"
Sub CreateMacro()
Dim cBut
Call KillMacro
Set cBut = Application.CommandBars("Cell").Controls.Add(Temporary:=True)
With cBut
.Caption = strMacro
.Style = msoButtonCaption
.OnAction = "Test_Macro"
End With
End Sub
Sub Test_Macro()
MsgBox "I work"
End Sub
Sub KillMacro()
On Error Resume Next
Application.CommandBars("Cell").Controls(strMacro).Delete
End Sub

For Microsoft Word 2007, I have pasted the macro code to add a custom menu option in the right click mouse event and getting the selected text into the function.
Macro:
Option Explicit
Sub CreateMacro()
Dim MenuButton As CommandBarButton
With CommandBars("Text")
Set MenuButton = .Controls.Add(msoControlButton)
With MenuButton
.Caption = "Press Me"
.Style = msoButtonCaption
.OnAction = "Test_Macro"
End With
End With
End Sub
Sub Test_Macro()
MsgBox Selection.text
End Sub
Sub ResetRightClick()
Application.CommandBars("Text").Reset
End Sub

Related

VBA to change the name of the Activex button

I am not sure, even if this is possible. I would like to change the named of the button when clicked.
I have Active X button that will enable cells on the sheet when clicked. Name of the button "Enable Sheet".
Once he enables, he should see a button "Disable Sheet". Please advise.
assuming your button is named after "CommandButton1":
Private Sub CommandButton1_Click()
With Me.OLEObjects("CommandButton1").Object
.Caption = IIf(.Caption = "Enable Sheet", "Disable Sheet", "Enable Sheet")
End With
End Sub
edited after OP's comments
Private Sub CommandButton1_Click()
With Me.OLEObjects("CommandButton1").Object
.Caption = IIf(.Caption = "Enable", "Disable", "Enable")
Range("E13:E14").Locked = .Caption = "Enable"
End With
End Sub
In the code that you can attach to the ActiveX object, you can try something like this:
Private Sub CommandButton1_Click()
Me.CommandButton1.Caption = "Enable"
End Sub
In general, for ActiveX Objects, you can change the displayed text using the .Caption property.

Cannot run the macro… the macro may not be available in this workbook VBA

My question at hand is why do these Macros for creating Menu Command buttons work on my personal computer (Excel 2010/2016), but generate macro may not be available messages on my work one. My only thoughts are it's relative to the bit /configuration of my work laptop, some various complier issue tied to old VBA libraries, assignment references being missed, & something random related to private Subs.
Macros in This Workbook. The coding is done in This Workbook, Module, & User Form (Command Button) . The VBA essentially programs a new button on the Excel Ribbon (Menu Commands) that when you click it an user form will generate. However, this does not happen with the VBA error. In overall, the coding is very sound. Therefore, I believe the errors I'm getting are tied to system/configuration items.
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
RemoveMenuItem
End Sub
Private Sub Workbook_Open()
AddMenuItem
'frmMain.Show
End Sub
MODULE
Option Explicit
Sub Selectfile()
Dim wb As Workbook
Set wb = Workbooks.Open("C:\Users\brian\Desktop\practice file2.xlsm")
End Sub
Sub AddMenuItem()
Dim cmbWorkSheetMenuBar As CommandBar
Dim cmbControl As CommandBarControl
Set cmbWorkSheetMenuBar = Application.CommandBars("Worksheet Menu Bar")
Set cmbControl = cmbWorkSheetMenuBar.Controls.Add(Type:=msoControlButton, temporary:=True) 'adds a menu item to the Menu Bar
With cmbControl
.Caption = "Show Form" 'names the menu item
.OnAction = "ShowTheForm" 'runs the specified macro
.FaceId = 1098 'assigns an icon to the dropdown
End With
End Sub
Sub RemoveMenuItem()
On Error Resume Next 'in case the menu item has already been deleted
Application.CommandBars("Worksheet Menu Bar").Controls("Show Form").Delete 'delete the menu item
End Sub
Sub ShowTheForm()
frmMain.Show
End Sub
UserForm Click Code
Option Explicit
Private Sub btnOne_Click()
Application.FindFile
End Sub

How make VBA run on clicking any checkbox in a userform?

I have a userform with a multiple frames, all filled with multiple checkboxes. I've named the checkboxes to their corresponding Excel cells. Now I want to make VBA run on clicking any of these checkboxes on run time. I know I can do this by creating a click-sub for every individual checkbox, but there must be a cleaner way to do this.
So far I've tried to put this code in the userform_Click and userform_Mousedown events, but they don't run when I click the checkboxes. Does anyone have an idea how to do this?
Dim iControl As Control
For Each iControl In Me.Controls
If TypeName(iControl) = "CheckBox" Then
If iControl.Value = True And Range(iControl.Name).Value = "" Then
Range(iControl.Name).Value = Format(Now, "dd.mm.yyyy")
ElseIf iControl.Value = True And Range(iControl.Name).Font.Color = vbWhite Then
Range(iControl.Name).Font.Color = vbBlack
ElseIf iControl.Value = False And Range(iControl.Name).Value <> "" Then
Range(iControl.Name).Font.Color = vbWhite
End If
End If
Next
As SilentRevolution said - you need an event to fire when you click the button. You're just after a single procedure to fire all check box click events.
So:
Create a class module called cls_ChkBox.
In the class module you'll add the Click event code:
Option Explicit
Private WithEvents chkBox As MSForms.CheckBox
Public Sub AssignClicks(ctrl As Control)
Set chkBox = ctrl
End Sub
Private Sub chkBox_Click()
ThisWorkbook.Worksheets("Sheet1").Range(chkBox.Name).Value = Format(Now, "dd.mm.yyyy")
End Sub
Now you just need to attach the chkBox_Click event to each check box on your form. In your user form add this code:
Option Explicit
Private colTickBoxes As Collection
Private Sub UserForm_Initialize()
Dim ChkBoxes As cls_ChkBox
Dim ctrl As Control
Set colTickBoxes = New Collection
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CheckBox" Then
Set ChkBoxes = New cls_ChkBox
ChkBoxes.AssignClicks ctrl
colTickBoxes.Add ChkBoxes
End If
Next ctrl
End Sub
Each check box is given its own instance of the class, which is stored in the colTickBoxes collection.
Open the form and the cell in Sheet1 will update to show the date depending on the name of the check box.
You need an event to run code, if there is no event, the macro cannot start. I don't know if there is a single event that triggers for any button or checkbox that is clicked.
If the code you want to execute is the same every time except the control, you could write a private sub in the userform module which is called for each event, the private sub can take an input between the () for example.
Private Sub CheckBox1_Click()
Call ExecuteCode(Me.CheckBox1)
End Sub
Private Sub CheckBox2_Click()
Call ExecuteCode(Me.CheckBox2)
End Sub
Private Sub CheckBox3_Click()
Call ExecuteCode(Me.CheckBox2)
End Sub
Private Sub ExecuteCode(IControl As Control)
If TypeName(IControl) = "CheckBox" Then
If IControl.Value = True And Range(IControl.Name).Value = "" Then
Range(IControl.Name).Value = Format(Now, "dd.mm.yyyy")
ElseIf IControl.Value = True And Range(IControl.Name).Font.Color = vbWhite Then
Range(IControl.Name).Font.Color = vbBlack
ElseIf IControl.Value = False And Range(IControl.Name).Value <> "" Then
Range(IControl.Name).Font.Color = vbWhite
End If
End If
End Sub
I just learned this today and thought it might help? Most of the questions, and responses for that matter, to questions regarding checkboxes, listboxes, etc. seem to not distinguish between those forms are inserted directly on the worksheet or are imbedded in a UserForm.
This may work for a checkbox - it works for a ListBox on a UserForm. If you want code to run after a selection, the code you must write has to be in module of the UserForm. I had no clue how to access. Once you have inserted a UserForm in your VBE, add the ListBoxes or whatever to the UserForm. Right click on the UserForm in the upper left project window and select "view code." Here is where you'll place the code, in my case a "change event" such that after a selection is made from the ListBox, other code is automatically run. Her for example:
Sub lstBoxDates_Change()
Dim inputString1 As String
inputString1 = Format(UserForm1.lstBoxDates.Value, "mm-dd-yyyy")
Call EnterDates(inputString1)
Unload Me
End Sub
To explain: Again this code is in the UserForm Module. I named my ListBox,
lstBoxDates. In my main code that I call - EnterDates, I use the variable name = inputString1. The value or date that I have selected from the ListBox is captured from the UserForm1 by UserForm1.lstBoxDates.Value - and I format that to a date, otherwise you see just a number. This is for only one selection.
Because I Dim here, no need to Dim in your main code. The sub for the main code
needs to accept the variable you are passing to it:
Sub EnterDates(inputString1)
This is very generalized but maybe something will click so you can get what you are after. I hope so, for I've worked on this a full two days!!

How to open a spreadsheet in Excel?

How can I make that, when pressing the command button, it opens the first spreadsheet of Excel?
I am coding in Visual Basic Forms in Excel 2016. This is my code:
Private Sub OptionButton1_Click()
If OptionButton1.Value = True Then MsgBox (" Has decidido Actualizar el Inventario")
Workbook("Hoja1").ShowAllData
End Sub
The code can be simplified into this:
Sub firstSheet()
Sheets(1).Select
End Sub
Then go to the Developer tab, add a button, and assign it to this macro.

Calling a macro from a button in edit mode while in PowerPoint

I'm trying to write a vba macro that can be called in edit-mode in PowerPoint 2007-2010.
I can easily add a Command Button to a presentation. However, this button can only be clicked to trigger the vba macro while in slideshow mode.
However, what I would like to do is have this button trigger the associated vba macro while in edit mode. Clicking on it in edit mode allows me to change its size etc, but it doesn't call the macro.
In Excel on the other hand, I get exactly the expected behaviour when I insert a button -> clicking on it calls the vba action.
So how can I create a button (or other element that acts the same way) that calls a vba macro during edit view in PowerPoint. The only way I can think of is using a ribbon action, however this is unpractical in this case, because the macro will modify a shape that is associated with the button and there might be several of these shapes per slide that should each have their own button.
The only way I can think of is using a ribbon action, however this is unpractical in this case, because the macro will modify a shape that is associated with the button and there might be several of these shapes per slide that should each have their own button.
Depending on what you're trying to do, a ribbon button that launches a macro might be quite practical. The macro could operate on the current selection (and test the current selection to ensure that it's something appropriate).
With ActiveWindow.Selection.ShapeRange
' operate on the currently selected shapes
End with
just answer it a some where else also
it is possible to do so all you need is download this file
http://www.officeoneonline.com/eventgen/EventGen20.zip
install it
create a class module
paste this code
Option Explicit
Public WithEvents PPTEvent As Application
Private Sub Class_Initialize()
End Sub
Private Sub PPTEvent_WindowSelectionChange(ByVal Sel As Selection)
If Sel.Type = ppSelectionShapes Then
If Sel.ShapeRange.HasTextFrame Then
If Sel.ShapeRange.TextFrame.HasText Then
If Trim(Sel.ShapeRange.TextFrame.TextRange.Text) = "Text inside your shape" Then
Sel.Unselect
yoursub
End If
End If
End If
End If
End Sub
insert a new module
paste this code
Dim cPPTObject As New Class1
Dim TrapFlag As Boolean
Sub TrapEvents()
If TrapFlag = True Then
MsgBox "Already Working"
Exit Sub
End If
Set cPPTObject.PPTEvent = Application
TrapFlag = True
End Sub
Sub ReleaseTrap()
If TrapFlag = True Then
Set cPPTObject.PPTEvent = Nothing
Set cPPTObject = Nothing
TrapFlag = False
End If
End Sub
Sub yoursub()
MsgBox "Your Sub is working"
End Sub
Now run TrapEvents and whenver you will click shape with that text in it your sub will run
Credits to the person who wrote this http://www.officeoneonline.com/eventgen/eventgen.html