How to use VBA to add a button to a sheet and assign its click event upon another button press - vba

I am trying to automate a quarterly patient report for a local pharmacy and in doing so I have transferred it to excel. One portion of the automation is an add patient button on the cover page of the report that goes to a form for relevent information. The ok button on the form takes the information and formats it in a new sheet named according to the patient's name. The button also adds two newly created buttons to the patient sheet, a delete and edit button. I can create the buttons and place them, but I can not find any way to assign a click event to the buttons, since they are considered new objects on each page.
I have moved the button's main code to the workbook itself, so all I really need to put in the button's click event is a call to that method, but I can't find any way to access the new buttons' click events through vba, and since I need to call a method in VBA itself, I'm not sure I can use a macro either (fair note, I am not all that familiar with excel macros, so if the solution lies in them, I can use that too).
Here is the code that instantiates and places/sizes the delete button on the new sheet:
Dim btn As OLEObject
Set btn = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False)
With btn
.Name = "deletePatientButton"
.Object.Caption = "Delete Patient"
.Top = 5.25
.Left = 290.25
.Width = 75
.Height = 24.75
.PrintObject = False
End With
Here is the main method of the delete button placed in the workbook code itself (note it only really calls another verification form, so this may be redundant, but I wanted to put it in the workbook section for testing since I assumed it would have the largest scope):
Public Sub mainDeleteButton(sheet As Worksheet)
Dim confirmer As New deleteConfirmationForm
sheet.Activate
confirmer.Show
End Sub
Finally, here is an example of the click event I am hoping to be able to place, or replace with another solution:
Private Sub deletePatientButton_Click()
Call ThisWorkbook.mainDeleteButton(Me)
End Sub
Any help is more than appreciated!

It is possible to add the event code programmatically to the worksheet module (see this post). However, it may be easier to keep your buttons on template worksheets that already have the event code in them. Just copy your template to a new sheet, rename it, and add your patient data.

Related

Get value from command button VBA

I have created A userform with few command buttons.
I can't seem to figure out how do I get the information from them.
I want to open this userform from another one and then I want the user to choose an option from one of the buttons which will change a specific cell in the table itself
the userform I created
I did not write anything on this userform therefor there is no code from it to show only the design.
how do get the information from the buttons to be written in A specific cell on a specific worksheet?
double click on one of the buttons, in the code menu a new sub should appear. this looks something like:
Sub CommandButton1_onClick()
End sub
Alongside this event method, it also has a few properties. The one that is usefull here is the CommandButton1.Value, this represents the state of the button (either true or false iirc).
So build for each button (I strongly advice giving them custom names to prevent getting lost in the trouble) as sub like this:
Sub CommandButton1_onClick()
if CommandButton1.Value then
ThisWorkBook.WorkSheets("WorksheetName").Range("YourRange").Value = "Some value"
else
ThisWorkBook.WorkSheets("WorksheetName").Range("YourRange").Value = ""
end if
End sub

Create a dynamic button via VBA at runtime

I created a Userform, that shows a few values from the table (within textboxes) that can be edited and a command button to save those changes back into the table.
Since I use the same template for various values I decided to dynamically create the Userform at runtime. But I can't get the command button to work at all. I cross-checked with various examples (on StackOverflow and other sites, e.g. here and here), but I can't find the problem.
This is my (simplified) code. The procedure is being called by a button click event itself (CommandButton1). As a workaround, I created a static (empty) UserForm UserForm1 which I use as a starting point to create a specific configuration of the form dynamically during runtime. Essentially it means that just the form elements are created dynamically. At least for now, but that's fine since I only need one single instance of the form to be displayed at any given time. Eventually, I would like to create the form at runtime too:
Private Sub CommandButton1_Click()
'Set Form
UserForm1.Caption = "Test"
'Create Form-Elements (Commandbutton)
Dim cmdButton01 As MSForms.CommandButton
Set cmdButton01 = UserForm1.Controls.Add("Forms.CommandButton.1", "dynCmdButton01")
cmdButton01.Width = 50
cmdButton01.Caption = "Save"
'Show Form
UserForm1.Show
End Sub
Private Sub dynCmdButton01_click()
MsgBox "Test"
End Sub
You should create a class module and assign the event through it:
dynamically create buttons and assign code for the click event (during runtime)
dynamically assign code to static buttons

VBA Executing Sub Oddly

I have made this simple invoice control worksheet in excel and I use VBA to make it easier to visualize and add new items. I have made dozens of other VBA programmed Worksheets, and all of them have a "New" active x button, programmed just like this:
Private Sub ButtNew2_Click()
Dim Guia As Worksheet
Dim UltLin As Integer
Set Guia = Workbooks("Notas Fiscais.xlsm").Worksheets("SaĆ­da")
UltLin = Guia.UsedRange.Rows.Count + 1
Guia.Application.Goto Reference:="R" & UltLin & "C1"
FormNotasSaida.Show
FormNotasSaida.BoxDataEmiss.SetFocus
End Sub
Simple as that. Just select the first blank line so that the form loads blank. It works fine in any other Workbook. But in this one, if and every time I click this button, after closing the form, the next time (and only once) I load the form again in any possible way (either double clicking an item, pressing the "Show" button or pressing the "New" button again), it loads either blank or showing the last launched item (case you did so).
After closing it, I can click wherever or press the "Show" button whenever, they work fine, as they always have. The problem occurs exclusively once, after pressing the "New" button.
What am I possibly doing wrong, specially knowing that this method works perfectly in all other workbooks?
FormNotasSaida.Show
FormNotasSaida.BoxDataEmiss.SetFocus
Forms are a special kind of class modules with a designer and a predeclared ID attribute. This "predeclared ID" is what's at play here: you're using/reusing the default global instance of the class, and [unless you close it with the X button in the control box,] never unload it so you're always showing the same form.
A best practice is to create a new instance of the form every time you use it:
Set frm = New FormNotasSaida
frm.Show
frm.BoxDataEmiss.SetFocus

Can i launch userform from a button in a Sheet

Pop up charts in VBA Excel
I was very curious with the answer in the above link.
My question is, Can I pop up a graph with click of button(The button is on Sheet1) and when i go bach to
Sheet thr graph is gone
Pertinent to your question as it is worded in the Title (i.e. 'Can i launch userform from a button in a Sheet'), you can implement this functionality in two simple steps:
1). From Excel 'Developer' tab select Insert -> Button. By default, it will create a new Button1 and corresponding Click event handle will be added to the Module1
Sub Button1_Click()
End Sub
2). Provided that you have a User Form named UserForm1, add a single statement in that event handle that will open the UserForm1 on Button click:
Sub Button1_Click()
UserForm1.Show
End Sub
In case you are trying to implement additional functionality, please include your code snippet highlighting the problematic part.
Hope this will help. Best regards,
Let's do it by point and basing on the answer you have posted.
Can I pop up a graph with click of button(The button is on Sheet1)?
Yes, you can. You need to:
Put a Button on Sheet1 and associate to it a macro, let's say popUpChart;
Create and show the chart:
Sub popUpChart()
Dim ch As UserForm1
Set ch = New UserForm1
'ch.CommandButton1_Click()
'a) Uncomment the line above if you want to invoke the button press before to show the chart
'b) If you decide to uncomment, remember to change the sub from "Private" to "Public"
ch.Show
End Sub
when i go bach to Sheet thr graph is gone
I don't understand well what you mean here. Do you mean "I want the graph to be gone when I go back to the sheet" or "I would like the chart to stay here but actually it's gone?
a) In the first case, it's enough to remove the image from the Image control of the form;
b) In the second case, it's enough to remove the Set statement from the button's macro.

How to reset Excel internal button count?

I have an an Excel sheet that uses VBA to generate some form control buttons on the fly.
the buttons are cleared and then new buttons are created.
I have noticed that even though old buttons are deleted Excel is keeping an internal register of each button. New buttons have button name of over 11K
I don't know if there is some sort of limit excel will allow for this and I don't want to run out of buttons.
I am not sure if this growing registry of buttons past is causing the file size to grow.
I would like to be able to reset the increment back to 0
Anyone have any idea how I can go back to button_0 ? (without starting a whole new Excel sheet)
Seems internal button count is sheet specific. Solution is to copy sheet, rename old sheet, then rename new sheet to old sheet name. Then delete old sheet. Viola! button count reset.
I found the answer somewhere in a forum, but I couldn't retrace it.
You could also pragmatically create the button by a function/sub-routine as a workaround.
Example: below function adds a button and limits the count to a fixed number (in my case, it is the total buttons available).
In my sheet, the first button is named "Button 687" (before I use the macro) and the second button is named "Button 2".
But, it is quite not dynamic when you want to add Drop Down or other form control etc. Macro recording helps you figure out the syntax, methods and properties of the form control you want to add though.
I am not sure why "buttons" is not listed in Properties/Methods after you typed "Activesheet." but Activesheet.Buttons(1).Name or Activesheet.buttons.add are valid codes.
Public Sub Add_Button(ButtonLabel$, ButtonSize#, BFontSize#, BFontName$)
Dim Button__ As Object
Dim One_Unit#: Per_Unit = Application.CentimetersToPoints(1)
'Creates a button at the sheet's first cell (row 1, col 1) with the height and width being 1cm.
Set Button__ = ActiveSheet.Buttons.Add(1, 1, One_Unit, One_Unit)
'button count will be restricted to the number set by user.
With Button__
.Name = "Button " & ActiveSheet.Buttons.Count
With .Characters
.Text = UCase(BLabel)
.Font.Name = BFontName
.Font.Size = BFontSize
End With
End With
End Sub
Sub AddAButton()
Add_Button BLabel:="SAVE"
Debug.Print ActiveSheet.Buttons(ActiveSheet.Buttons.Count).Name
End Sub