Is there any way to insert a user form directly on the excel sheet?
We can add the build-in controls as well as active x controls. I don't see why we cannot add user forms within the same workbook.
Thanks
No, I don't think it's possible.
Userforms are merely containers to hold your ActiveX controls. Spreadsheets are also ActiveX control containers, so I'm not sure what the benefit of having a container in a container would be.
You could easily color a group of cells to look like a userform and place ActiveX controls within that range. That would simulate a userform embedded on a spreadsheet. You'd be missing userform level events and probably a few other things. But if you wanted those things, you'd probably just use a userform.
If there's something you want to do that I'm missing, let me know.
Place this in the WorkSheet module
VB:
Private Sub Worksheet_Activate()
UserForm1.Show
End Sub
I realize it's an old post and this solution might not have been available in the past but you can insert an ActiveX control element and have "Microsoft Forms 2.0 Frame" to control the information.
You will also need to create a custom class to handle the button presses since you can't attach macros directly onto them like a normal button.
Here is an example of mine:
buttonEventHandler
Option Explicit
Public Sub Click(Sender As Integer)
End Sub
xButton
Private WithEvents btn As MSForms.commandButton
Private bEventHandler As buttonEventHandler
Private b As Integer
Public Sub createObject(EventHandlerOf As MSForms.commandButton, EventHandler As buttonEventHandler, xB As Integer)
Set btn = EventHandlerOf
Set bEventHandler = EventHandler
b = xB
End Sub
Private Sub btn_Click()
If Not bEventHandler Is Nothing Then bEventHandler.Click (b)
End Sub
in Microsoft Excel Objects: thisWorkbook
Public Sub buttonEventHandler_Click(Sender As Integer)
Select Case Sender
Case 1
'Do Stuff
End Select
End Sub
Private Sub workbook_open()
Sheet1.Frame1.Activate
Set xbtn = New Collection
Dim o As Object
Dim xB As New XButton
xB.createObject Sheet1.Frame1.Controls("excelCommandButton"), ThisWorkbook, 1
xbtn.Add xB
Set xB = Nothing
End Sub
You could place MyForm.Show code on the Workbook.Open event to launch the form whenever you open the file... that I've done. You can even choose where to place the form.
Your wish, if possible (I'm pretty positive it's not), could trigger concurrent VB code: e.g. auto-calculate of cells, and the form code. That's an issue because XL is single VBA thread, hence it's impossible to have two things happening. Either the form is showing and it's code is running, or XL application is running and doing cells/graphs/etc stuff.
Related
I added code to a series of similar files for different projects.
I defined a (Control + R) "^ + R" shortcut to let users see the current record in a userform.
I added application.key code on workbook activating and deactivating event, so the shortcut can be used when several files of this type are open.
My problem is even if the form opens and reads the data from the respective workbook, the userform is not called from the respective file!
Should I localize the procedure as well?
Here are my codes:
The Code in ThisWorkbook
Private Sub Workbook_Activate()
With Application
.OnKey "^R", "ReadCurrentRecord"
End With
End Sub
Private Sub Workbook_Deactivate()
Application.OnKey "^R"
End Sub
The Code in a general Module
Sub ReadCurrentRecord()
If ActiveCell.Worksheet.Name = "OSW" Then
If OSWRng Is Nothing Then
Set OSW = ThisWorkbook.Sheets("OSW")
Set OSWRng = OSW.Range("a5:bz2000")
End If
FrmWODetails.Tag = OSW.Cells(ActiveCell.Row, 14)
FrmWODetails.UserForm_Activate
FrmWODetails.Show vbModeless
End If
End Sub
All the Names are same in the files.
thisworkbook and activecell may not be what you expect them to be.
if this is an addin, this workbook will refer to the addin while active cell wont. i don't even know if activate a cell can be used in an add-in' sheet... I'm thinking not, I'll test that then i get to s computer for my own knowledge.
it's almost always best to fully qualify the object, sometimes from the application level but normally the workbook will suffice
personally, I prefer codenames over names and babes over indexes but they have a few drawbacks that keep them from being my#1 choice
I have multiple buttons (active x) on a spreadhseet in same column but different rows. These buttons capture the start time of an activity.
If button 1 is pressed cell next to it should be populated by current time.
If button 2 is pressed cell next to it should be populated by current time. and so on.....
I have written a SUB in VBA as follows:
Private Sub StartTimer_Click()
Range("I4").Value = Now
End Sub
I do not want to repeat this code for each button action. Please let me know how it can be made dynamic.
A simple WithEvents example:
in a class (named clsButtons):
Private WithEvents Bt As MSForms.CommandButton
Property Set obj(b As MSForms.CommandButton)
Set Bt = b
End Property
Private Sub Bt_Click()
'uses the right of the name of the CommandButton
Cells(1 + Right(Bt.Name, 1) * 3, 9).Value = Now
End Sub
In the sheetcode (the one with the buttons):
Dim myButtons As Collection
Private Sub Worksheet_Activate()
Dim ctl As OLEObject
Dim ButtonClass As clsButtons
Set myButtons = New Collection
For Each ctl In Sheet1.OLEObjects
If ctl.progID = "Forms.CommandButton.1" Then
Set ButtonClass = New clsButtons
Set ButtonClass.obj = ctl.Object
myButtons.Add ButtonClass
End If
Next ctl
End Sub
Create a standard module and put the procedure in there.
While it is possible to share a procedure in a private module, it's best practice to put any shared procedures in a shared module.
In the VBA Editor click Insert > Module,
Paste into there, and give it a unique name. Using your example you could do something like:
Public Sub SetTimeValue()
Range("I4").Value = Now
End Sub
...then call this public stub from your other one, like:
Private Sub StartTimer_Click()
SetTimeValue
End Sub
...and from any other locations where you need to call your code.
I assume that you have more than one line of code for the actual procedure you're concerned about, otherwise copying it repeatedly isn't really a concern.
More Information:
MSDN : Understanding Scope and Visibility
Office Support : Scope of variables in Visual Basic for Applications
Chip Pearson : Understanding Scope Of Variables And Procedures
PowerSpreadsheets : Excel VBA Sub Procedures: The Complete Tutorial
MVP : Cut out repetition using subs and functions with arguments
I have a worksheet that runs a weightlifting meet. Last year I had created a tab that would give information on the current lifter and on who was lifting next.
left side - Display, right side - input tab
When I input an "x" in columns R, S, T, or W on the data tab, it changes the information in the BenchGenerator tab, like so:
Updated Display tab
What I want to do is make a userform display to run on a different screen so people can see this information. I had accomplished this last year by widening excel and using two view windows - display on the second screen and running the meet on the computer. It was ok but very clunky looking. With a floating userform tab, it would look fantastic. I am new to this, but got the form floating:
Private Sub Worksheet_Change(ByVal Target As Range)
UserForm1.Show (vbModeless)
End Sub
And got the labels to initially populate:
Userform Display
Using this code:
Private Sub UserForm_Activate()
UserForm1.Label1.Caption = Sheets("BenchGenerator").Range("c4").Value
UserForm1.Label2.Caption = Sheets("BenchGenerator").Range("c5").Value
UserForm1.Label3.Caption = Sheets("BenchGenerator").Range("c6").Value
UserForm1.Label4.Caption = Sheets("BenchGenerator").Range("d3").Value
UserForm1.Label5.Caption = Sheets("BenchGenerator").Range("d4").Value
UserForm1.Label6.Caption = Sheets("BenchGenerator").Range("d5").Value
UserForm1.Label7.Caption = Sheets("BenchGenerator").Range("d6").Value
End Sub
What it doesn't currently do is update the captions when I input the "x" in the data tab.
As I mentioned, this is my first foray into userforms and looking through mountains of code trying to figure this out, it will not be my last as there is lots to accomplish with them.
Thanks in advance for any help!
You're pretty close to getting this to work. The problem is that your calling a new form every time a change occurs.
Declare your form as an object outside of the Sub that creates (Show) it.
You can then access it to update labels from another Sub that has the same scope.
Create an UpdateForm sub for example and call it from your Worksheet_Change event.
Try this, place the following code in a new Module:
Dim myForm As Object
Sub launchForm()
Set myForm = UserForm1
myForm.Show (vbModeless)
End Sub
Sub updateForm()
Dim wks As Worksheet
Set wks = Sheets("BenchGenerator")
'Update label values here
myForm.Label1.Caption = wks.Range("C4").Value
myForm.Label2.Caption = wks.Range("C5").Value
myForm.Label3.Caption = wks.Range("C6").Value
myForm.Label4.Caption = wks.Range("D3").Value
myForm.Label5.Caption = wks.Range("D4").Value
myForm.Label6.Caption = wks.Range("D5").Value
myForm.Label7.Caption = wks.Range("D6").Value
End Sub
If you use Worksheet_Change to update the form you'll want to verify the form exist or just skip any errors in the event if it doesn't.
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
updateForm
End Sub
Not sure if there is an easier way to do it, but I made a concatenation routine to batch out my label setup and updates to quickly create/copy/paste all the code.
Just in case anyone didn't know how to do this
I am looking to write a macro which copies formatting from one graph and applies it to multiple other graphs.
What I am struggling to do is determine a way to allow the user to set the template chart and then select the multiple other charts. While this could be done with a combo box if the user knew the chart name, I am trying to do it without them knowing the chart name.
As such I was thinking of having a user dialog box where the user can select the base chart, and then select the charts to apply the formatting to. Just like refedit for a range. However I cannot figure out how to reference to a graph from within a user form.
Can this be done, and if so, how?
Here is what will get you started.
Place Two ComboBoxes and two Image Controls on the userform.
Let's say your worksheet looks like this
In the UserForm_Initialize() event populate the Chart names in both the comboboxes. For example
Dim ws As Worksheet
'~~> Prepare your form
Private Sub UserForm_Initialize()
Set ws = ThisWorkbook.Sheets("Sheet1")
Dim ChartObj As ChartObject
For Each ChartObj In ActiveSheet.ChartObjects
ComboBox1.AddItem ChartObj.Name
ComboBox2.AddItem ChartObj.Name
Next ChartObj
End Sub
So when you run the form, it will look like this
In the click event of the comboboxes, use the Stephen Bullen's PastePicture code from HERE to show the chart in the userform. For example
Private Sub ComboBox1_Click()
ws.Shapes(ComboBox1.Value).CopyPicture
Set Me.Image1.Picture = PastePicture(xlPicture)
End Sub
Private Sub ComboBox2_Click()
ws.Shapes(ComboBox2.Value).CopyPicture
Set Me.Image2.Picture = PastePicture(xlPicture)
End Sub
This is how the form will look.
From there on, Now you have the names of the charts. Simply use them to work as you please.
Hope this helps.
The following code should allow you to do stuff with the selected chart area(s), where you can either select one or many charts:
Public Sub ProcessSelectedCharts()
Dim i As Integer
Dim chart_obj As ChartObject
Dim chart_area As chartArea
If TypeOf Selection Is DrawingObjects Then
For i = 1 To Selection.Count
If TypeOf Selection(i) Is ChartObject Then
Set chart_obj = Selection(i)
Set chart_area = chart_obj.Chart.chartArea
Call ProcessChart(chart_area)
End If
Next i
ElseIf TypeOf Selection Is chartArea Then
Set chart_area = Selection
Call ProcessChart(chart_area)
End If
End Sub
Public Sub ProcessChart(obj As chartArea)
' Do something...
End Sub
You may want to refine this a little, i.e. this should work if the user selects the actual charts, but may fail if he only selects a particular element within the chart.
Ok, the next question is, when do you invoke this from your user form. So first of all, your user form should be modal of course, to allow the user the select anything. So how do you notice when the users actually selects anything?
I can think of three methods, and I'll list them from best to worst (the last 2 only described very briefly as I wouldn't recommend using them):
Use the "Worksheet_SelectionChange" event on your worksheet, and have it call a method within your userform to inform it that the selection has changed. Now you'll just need to check if, and which charts have been selected (see code above), and run your algorithm.
Run a timer in your userform and regularly check the active selection.
Hook mouse events by DLL calls and register any mouse clicks, then check for selection changes.
That should allow you to create a ref-edit like feature for selecting charts on your worksheet from a userform.
I have a thousands of cells in an Excel worksheet which are ComboBoxes. The user will select one at random and populate it.
How do I get the selected ComboBox value? Is there a way to trigger a function (i.e. an event handler) when the ComboxBoxes has been selected?
You can use the below change event to which will trigger when the combobox value will change.
Private Sub ComboBox1_Change()
'your code here
End Sub
Also you can get the selected value using below
ComboBox1.Value
If you're dealing with Data Validation lists, you can use the Worksheet_Change event. Right click on the sheet with the data validation and choose View Code. Then type in this:
Private Sub Worksheet_Change(ByVal Target As Range)
MsgBox Target.Value
End Sub
If you're dealing with ActiveX comboboxes, it's a little more complicated. You need to create a custom class module to hook up the events. First, create a class module named CComboEvent and put this code in it.
Public WithEvents Cbx As MSForms.ComboBox
Private Sub Cbx_Change()
MsgBox Cbx.Value
End Sub
Next, create another class module named CComboEvents. This will hold all of our CComboEvent instances and keep them in scope. Put this code in CComboEvents.
Private mcolComboEvents As Collection
Private Sub Class_Initialize()
Set mcolComboEvents = New Collection
End Sub
Private Sub Class_Terminate()
Set mcolComboEvents = Nothing
End Sub
Public Sub Add(clsComboEvent As CComboEvent)
mcolComboEvents.Add clsComboEvent, clsComboEvent.Cbx.Name
End Sub
Finally, create a standard module (not a class module). You'll need code to put all of your comboboxes into the class modules. You might put this in an Auto_Open procedure so it happens whenever the workbook is opened, but that's up to you.
You'll need a Public variable to hold an instance of CComboEvents. Making it Public will kepp it, and all of its children, in scope. You need them in scope so that the events are triggered. In the procedure, loop through all of the comboboxes, creating a new CComboEvent instance for each one, and adding that to CComboEvents.
Public gclsComboEvents As CComboEvents
Public Sub AddCombox()
Dim oleo As OLEObject
Dim clsComboEvent As CComboEvent
Set gclsComboEvents = New CComboEvents
For Each oleo In Sheet1.OLEObjects
If TypeName(oleo.Object) = "ComboBox" Then
Set clsComboEvent = New CComboEvent
Set clsComboEvent.Cbx = oleo.Object
gclsComboEvents.Add clsComboEvent
End If
Next oleo
End Sub
Now, whenever a combobox is changed, the event will fire and, in this example, a message box will show.
You can see an example at https://www.dropbox.com/s/sfj4kyzolfy03qe/ComboboxEvents.xlsm
A simpler way to get the selected value from a ComboBox control is:
Private Sub myComboBox_Change()
msgbox "You selected: " + myComboBox.SelText
End Sub
Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)
sub myhandler(eventsource)
process(eventsource.value)
end sub
for each cell
cell.setEventHandler(myHandler)
But i dont know the syntax for achieving this in VB/VBA, or if is even possible.