Trying to edit the text of a form control label named lblsearchreminder and make sure that the font is Arial and size 20. I am pulling the edited text from an ActiveX textbox1 and trying to make that the caption of the label. If anyone has any insight I would greatly appreciate it.
Sub btnAltCustomSearch_Click()
Dim strTextBox As String
If Worksheets("User Interface").OLEObjects("TextBox1").Object.Value = "" Then
ErrorX.Show
Else
strTextBox = Worksheets("User Interface").OLEObjects("TextBox1").Object.Value
Worksheets("Muscle Wasting Database").Shapes("lblsearchreminder") = vbCrLf & "Disease: All" & vbCrLf & vbCrLf & "Keyword: " & strTextBox
lblsearchreminder.Object.Characters.Text = "Arial"
lblsearchreminder.Object.Font.Size = 20
End If
End Sub
Yes the textbox1 is an ActiveX textbox control, but I will ideally use a Form Control label. So I am trying to pull the typing from the ActiveX textbox and use it in the Form Control label – Thor Nagel 3 hours ago
Unfortunately you can't manipulate the font-size/name, color or style of a Form Control Label. If you notice the formatting items have been "grayed out" in the Font group on the Excel Ribbon.
To set a Text is easy
Dim lblsearchreminder As Shape
Set lblsearchreminder = Sheet1.Shapes("Label 1")
lblsearchreminder.TextFrame.Characters.Text = "Hello"
But you cannot do (Even though Intellisense allows it)
lblsearchreminder.TextFrame.Characters.Font.Name = "Arial"
or
lblsearchreminder.TextFrame2.TextRange.Characters.Font.Name = "Arial"
I would recommend using a TextBox shape or an ActiveX Label instead.
Similarly you cannot change the font using
lblsearchreminder.TextFrame.Characters.Font.Size= 20
I don't think you're using a Form Control. TextBox1 would be the default name for an ActiveX control, which would be coherent with using .OLEObject.Object to retrieve it.
Declare a MSForms.TextBox variable for it.
Dim box As MSForms.TextBox
Now assign it to the .OLEObject.Object:
Set box = Worksheets("User Interface").OLEObjects("TextBox1").Object
If the sheet "User Interface" exists in ThisWorkbook at compile-time, give it a code name (F4; set the (Name) property to e.g. UserInterfaceSheet) - then you can use that identifier directly, without needing to pull the worksheet from the Worksheets collection:
Set box = UserInterfaceSheet.OLEObjects("TextBox1").Object
Now you have an early-bound object reference to play with, you'll have IntelliSense to guide you. MSForms.TextBox does not have a .Characters property. It does have a .Font property though, so you can start exploring that:
So the Font property is an object of type NewFont; using the Object Browser (F2) you can browse its members:
Thus:
box.Font.Name = "Arial"
box.Font.Size = 20
Should do it.
Watch out for misleading names and prefixes: lblsearchreminder reads like you're looking at a MSForms.Label control, not a TextBox. txtSearchReminder would be more appropriate, or if you prefer control-agnostic names, SearchReminderBox works as well.
Also Error is a function from the VBA.Conversion module, that you are shadowing here.
Related
So pretty much what I am trying to do is create a floating text box that would be on the right of the spreadsheet. When a user selects a row/cell it will then place a comment or message with details about that cell in there rather than a small little comment box.
I have tried to use the UserForm Box but its not really what I'm looking for.
Example:
User Selects Cell A4, I would like a message to read in a floating text when that cell is selected. Then if a user selects Cell B6 a different message appears in that box.
Does that makes sense?
Update:
The Following Code Shows a UserForm box when a certain cell is selected:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim Definition As String
If Intersect(Target, Range("C6:D6")) Is Nothing Then Exit Sub
Select Case Target.Row
Case 22
Definition = "Text Here"
Case 23
Definition = "Text Here Again"
End Select
UserForm1.Label1.Caption = Definition
UserForm1.Show
End Sub
I don't want to use a UserForm box as its not stationary on the Worksheet itself. I want it so a Text Box that always appears on the right hand side of the worksheet to display a set message or context when the cell is selected. It will be different then what is stored in the actual cell.
Use a Data Validation message. This type of message "pops-up" whenever you click on a cell:
You can place a Label or TextBox control directly in the worksheet - make sure it's an ActiveX control, not a Forms control - and position it dynamically using the worksheet's SelectionChange event:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
With Me.lblText
.Visible = False
Select Case Target.Row
Case 22
.Caption = "Text Here Again"
Case 23
.Caption = "Text Here Again"
Case Else
.Visible = False
Exit Sub
End Select
' Place the label to the right of the target cell
.Left = Target.Left + Target.Width
' Or place the label in the far left of the window
'.Left; =; Application.ActiveWindow.VisibleRange.Width; -; .Width
.Top = Target.Top - 0.75 ' cell borders
.Visible = True
End With
End Sub
Some hints:
Make sure the 'Placement' property of a label is 2
(XlPlacement.xlMove), as other values give you Free-Floating or
Move-and-Size.
I strongly advise you to set the background colour of the control to
&H80000004&, the predefined Windows scheme colour for menu and form
backgrounds; likewise, the foreground to &H80000008&, the menu text
colour. This ensures visibility for users who have their own colour
settings, and explicitly supports users who specify an accessible or
assistive colour scheme to ameliorate a visual impairment.
My code relies on your sheet supporting event procedures in VBA, and
on ActiveX controls. It won't work in .xlsx sheets, and it may be
blocked (or accompanied by warning dialogues) if your operating
environment has a heavy-handed security policy.
Copy-and-paste might be affected by my use of the Worksheet
SelectionChange event.
Right-Click the control in design view for the 'Format Control' menu
and uncheck 'Print Control' - if the users print the sheet, they'll
want to see the cell contents, not the label.
Also: the label's in the way of selecting and editing the control
it's sitting over. Maybe you want it 4-5mm to the right, so the users
can get the mouse into that cell. Alternately, do this in the label's
Click() or MouseMove event:
Me.lblText.Visible = False
You might draw an obvious conclusion from all this: the native comment or data validation label is a better bet than using forms and ActiveX controls.
I have been creating an acronym finding macro that will sit on a custom toolbar in word. When run it searches the document for acronyms and places them in a table. I want to include some user forms so that as the macro finds an acronym the user can select the predefined definition (got from an excel document) or enter their own new one (I know multiple acronyms meanings is frowned upon but it happens).
Anyway I am stuck. I have created a user form with three buttons. A text input and a label. Now I have managed to set the label text with the acronym that was found however I can't seem to get the buttons to change a variable, userChoice, and if applicable save the newly entered definition.
below is the test macro i have been trying this out on
Sub userFormTest()
Dim objExcel As Object
Dim objWbk As Object
Dim rngSearch As Object
Dim rngFound As Object
Dim targetCellValue As String
Dim userChoice As Integer
Set objDoc = ActiveDocument
Set objExcel = CreateObject("Excel.Application")
Set objWbk = objExcel.Workbooks.Open("C:\Users\Dave\Documents\Test_Definitions.xlsx")
objExcel.Visible = True
objWbk.Activate
With objWbk.Sheets("Sheet1")
Set rngSearch = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(-4162))
Set rngFound = rngSearch.Find(What:="AA", After:=.Range("A1"), LookAt:=1)
If rngFound Is Nothing Then
UserForm1.Label1.Caption = "Acronym: AA" & vbCr & _
"Definition: Not found, please enter a definition below" & vbCr & _
" or choose to ignore this acronym"
UserForm1.Show
'an if statement here so that if the add button was pressed it adds to doc etc
Else
targetCellValue = .Cells(rngFound.Row, 2).Value
UserForm2.Label1.Caption = "Acronym: AA" & vbCr & _
"Definition: " & targetCellValue
UserForm2.Show
'an if statement here so that if the add button was pressed it adds to doc etc
End If
End With
objWbk.Close Saved = True
Set rngFound = Nothing
Set rngSearch = Nothing
Set objWbk = Nothing
objExcel.Visible = True
Set objExcel = Nothing
Set objDoc = Nothing
End Sub
I do realise that this could be done in the button_click() subs however I already have all the documents open etc in the other macro. Or is it possible to link to those already open documents? To be honest either way I would prefer to return to the main macro and just use the form to the user input.
I do realise that this could be done in the button_click() subs. However I already have all the documents open etc in the other macro. Or is it possible to link to those already open documents?
You can definitely link between button_click() subs and your main macro to modify the value of userChoice.
Answer:
What you need is some userform element (like a textbox) that can hold your value so you can refer back to it in your main macro. It looks like you already have this element (based upon your caption "Not found, please enter a definition below"). Let's say that element is a TextBox called Definition. Then let's say you want to return to the main macro after people push an "Add" button, as it appears you do (based upon your comment "so that if the add button was pressed it adds to doc").
In each of both Userform1 and Userform2, you would want something like this:
Private Sub AddButton_Click()
Userform1/Userform2.Hide
End Sub
That would return you to your main macro, where you could follow up with:
If Userform1/Userform2.Definition.Value = Whatever Then
'if the add button was pressed it adds to doc etc
End If
right where your existing comments are. Note that you could set userChoice = Userform1.Definition.Value here, but you don't need to because Userform1.Definition.Value already contains the information you need to track.
Additional material:
Rather than using the default instance of your Userform1 and Userform2 by using .Show on them immediately without assigning new instances of them to variables, may I suggest creating Userform variables to contain New instances of them like this:
Dim UnknownDefinition As Userform1
Set UnknownDefinition = New Userform1
UnknownDefinition.Show
Or if you want to get really optimal, you could follow more of the approach recommended here on how to make a properly instanced, abstracted userform:
Rubberduck VBA: How to create a properly instanced, abstracted userform
And now with bonus quotes from the post's author, #Mathieu Guindon:
make Definition a proper property, with the Property Let mutator changing the label value on top of changing its private backing field's value; avoid accessing form controls outside the form, treat them as private even if VBA makes them public.
Calling code wants data, not controls. You can extract properties/data, but not controls, into a dedicated model class.
I was using code at the bottom that I found on the Internet to add commands to the Word 2013 right-click menu. Now that I have used it I was hoping to understand it better and could someone explain some of the parameters to me. I want to understand it better and case I want to run it again to add more commands. The official Microsoft help reference only confuses me.
How does Before:=30 work? At first I thought it simply counted down from the top of the right-click menu, but when I did this my commands wound up in the wrong place. I think it must be counting commands that aren’t show all the time.
Are Tag:="Save" and .Tag = "Save" the same and what are they.
What is .Caption?
The above three parameters seem very similar.
Sub EditRightClickMenu()
'
'
'
Dim cb As CommandBar
Dim ctl As CommandBarButton
On Error GoTo bye
CustomizationContext = NormalTemplate
Set cb = CommandBars("Text")
Set ctl = cb.FindControl(Tag:="Save")
If ctl Is Nothing Then
Set ctl = cb.Controls.Add(Type:=msoControlButton, _
Before:=30, Temporary:=True)
With ctl
.Caption = "Save"
.Tag = "Save"
.FaceId = 3
.BeginGroup = True
.OnAction = "MySave"
End With
End If
bye:
End Sub
The Before:=30 is indeed the command on the menu before which you wish to insert the new control. If you remove the line On Error GoTo bye line from your code and run it on a normal word install you'll get an error trying to set the line:
Set ctl = cb.Controls.Add(Type:=msoControlButton, _
Before:=30, Temporary:=True)
This is because there aren't 30 controls on the default Text right click menu. Change it to 5 and it'll work fine.
Tag:="Save" and .Tag="Save" are slightly different. The Tag:= notation is used when specifying variable inputs to a method, in this case its the Tag input to the function of FindControl. If you press Shift+F2 on your keyboard when selecting FindControl in you editor it'll take you to the definition of the method and all the variables. The .Tag notation refers to an objects property, in this case the Tag is being set as "Save" so it can be found if the macro is run again.
Finally .Caption is merely the text displayed on the menu control once created.
I draw a simple label control directly onto the excel worksheet. But I can't seem to find any way to access it via code in the VBA editor. Is this even possible?
You may have drawn an ActiveX label or a Forms label. If it was the first label on the sheet then the following code will pick up the default "label1" name and either objActiveXLabel or objFormslabel will refer to your control
You could also experiment recording macros with the VBA recorder when inserting labels as this will give you pointers to the label type, and how to manipulate the label
Dim objActiveXLabel As OLEObject
Dim objFormsLabel As Shape
On Error Resume Next
Set objActiveXLabel = ActiveSheet.OLEObjects("Label1")
Set objFormsLabel = ActiveSheet.Shapes("Label 1")
On Error GoTo 0
If Not objActiveXLabel Is Nothing Then MsgBox "Found an ActiveX label", vbExclamation
If Not objFormsLabel Is Nothing Then MsgBox "Found an Forms label", vbExclamation
I want to allow users to be able to paste values into TextBoxes in a userForm in VBA. You can use Ctrl-v just fine, but not everyone knows how to do that.
How do I enable copy and pasting using a right-click menu?
I realize this is an old post but I believe there is a more efficient method.
Userform Contextual Menu class code
http://www.andypope.info/vba/uf_contextualmenu.htm
There are even sample excel spreadsheets for the code examples.
The class module handles the construction of the contextual menu, the capture of right clicking in textboxes and the actual Cut. Copy and Paste actions. The class makes use of the userform's ActiveControl object. The code even handles controls within container controls such as Frames and Multipage.
The follow Initialization code, from the userform, shows how simple it is to define and use the class object. You only need declare a variable to the object and then set a reference for each textbox you want to have contextual menu capabilities. You can loop through all controls and automatically reference each textbox.
Private m_colContextMenus As Collection
Private Sub UserForm_Initialize()
Dim clsContextMenu As CTextBox_ContextMenu
Dim cTRL as Control
Set m_colContextMenus = New Collection
For Each cTRL In Me.Controls
Select Case TypeName(cTRL)
Case "TextBox"
'MsgBox cTRL.Name & ": " & Me.Controls(cTRL.Name).Value
Set clsContextMenu = New CTextBox_ContextMenu
With clsContextMenu
Set .TBox = Me.Controls(cTRL.Name)
Set .Parent = Me
End With
m_colContextMenus.Add clsContextMenu, CStr(m_colContextMenus.Count + 1)
Case Else
'MsgBox TypeName(cTRL) & ": " & cTRL.Name
End Select
Next
End Sub
Download example workbook which contains both .xls and .xlsm files
This may be of interest: http://word.mvps.org/faqs/userforms/AddRightClickMenu.htm