Multiple text boxes to call the same VBA procedure - vba

I am developing an Access Database and have several forms; all of which have the same text box on them.
The text box for each form is from the same record source, same name, same properties, etc. After the textbox is updated I have VBA running an Instr procedure which captures key phrases commonly used in these text boxes and replaces them with a common phrase.
How can I get each text box from each form to call the same procedure, that way if I have to improve the code over time I am only doing so in one place versus going to each form to update the code.
Example code.
textbox1_AfterUpdate()
Dim A as TextBox
Set A= Me.Textbox1
If InStr(A," Attachment Number ") Then
Me.FunctionalArea.SetFocus
A=Replace(A,"Attachment Number","<<Att."&" "& Left(Me.FunctionalArea).text,1)&""&"XXX>>")
A=SetFocus
End If
If InStr(A, " Program Name ") Then
A = Replace(A, " Program Name ", " <<ProgramNameXX>> ")
End If
If InStr(A, " Office Address ") Then
A = Replace(A, " Office Address ", " <<OfficeAddressXX>> ")
End If

You just call the code with a parameter of the textbox.
Something along the lines of
Public Sub textbox1_AfterUpdate()
DoTextBoxActions Me.Textbox1
End Sub
Public Sub DoTextBoxActions(ByRef ipTextBox As TextBox)
If InStr(ipTextBox.Text, " Attachment Number ") Then
ipTextBox.FunctionalArea.SetFocus
ipTextbox=Replace(ipTextbox.Text,"Attachment Number","<<Att."&" "& Left(ipTextbox.FunctionalArea).text,1)&""&"XXX>>")
ipTextBox.Parent.SetFocus = SetFocus
End If
If InStr(ipTextBox.Text, " Program Name ") Then
ipTextBox = Replace(ipTextBox.Text, " Program Name ", " <<ProgramNameXX>> ")
End If
If InStr(ipTextBox.Text, " Office Address ") Then
ipTextBox = Replace(ipTextBox, " Office Address ", " <<OfficeAddressXX>> ")
End If
End Sub

You can do this.
When you place that text box on each form, in place of building a "event" code stub, you can enter this:
=MyFunctionName()
Or, thus in your case, you would place this code in a standard code module (NOT the forms code module).
Public Function MyGlobalAfterUpdate
' pick up the form and the control
' do this first, do this fast, do this right away
' since a timer event, mouse click, focus change etc. can
' case the screen.ActiveForm, and screen.ActiveControl to change
' once we grab these values, then you ok
Debug.Print "global after"
Dim MyControl As TextBox
Dim MyForm As Form
Set MyForm = Screen.ActiveForm
Set MyControl = Screen.ActiveControl
Debug.Print "Control name = " & MyControl.Name
Debug.Print "Text of control = " & MyControl.Value
Dim strText As String
strText = MyControl.Value
Debug.Print strText
' note that we have FULL use of the form values
' in place of me!Some value, or control?
' you can go
MyForm.Refresh
MyForm!LastUpdate = now()
' save the data in the form
' If MyForm.Dirty = true then MyForm.Dirty = False
End sub
So you are free to do whatever you want in this code. And you simple replace "me" the forms reference with MyForm, but once you grabbed the active form, then anything you would or could do with "Me", you can do the SAME with MyForm. As noted, you could in theory using Screen.ActiveForm, but you are MUCH better to pick up a reference as fast as possible and as soon as possible, since those values and focus could change, and often it will - so get/grab/take a reference to the controls as fast and as soon as possible. Once you grabbed the reference from screen, then minor changes in focus etc. don't matter - since you picked up the form and control right away.
The key concept, the key takeaway? you can grab both the current form with screen.ActiveForm, and you can get/grab the current control that fired the after update event with Screen.ActiveControl.
So, in summary:
Don't create a code stub in the form. In the controls after update event, place the name of the PUBLIC function in a STANDARD code module.
eg like this:
=MyGlobalAfterUpdate()

Related

MS Word VBA Macro from validation

I'm trying to do what, I think, ought to be the simplest of things, but I can't get it to work. i have an MS Word document with a number of legacy drop-down and text fields:
The first option in each drop-down is "Select ...", and if a user tabs out of one of the drop-downs without choosing something other than the first "Select ...", I want a msgbox to appear to tell them to make a selection, which works. What doesn't work, is that after the user dismisses the msgbox, I want the insertion point to return to the drop-down that they didn't select.
I understand that VBA has "timing issues", and from what I've read, one way to address these timing issues is to call the "return" macro from the validation macro. So I've written two macros:
Sub Validate()
' Dim strBookmark As String
' strBookmark = Selection.Bookmarks(1).Name
10: If (bool_debug) Then MsgBox ("NotSelected() - 10: strBookmark = " & strBookmark)
With ActiveDocument
If (strBookmark = "Locality") Then
Call Salary_Step
ElseIf (strBookmark = "Series") Then
20: If (bool_debug) Then MsgBox ("NotSelected() - 20: .FormFields(strBookmark).Name = " _
& .FormFields(strBookmark).Name)
If ((Len(.FormFields(strBookmark).Result) <> 4) Or (Not IsNumeric(.FormFields(strBookmark).Result))) Then _
MsgBox ("Please enter a 4 digit number.")
Call GoBackToPrevious(.FormFields(strBookmark).Name)
ElseIf (.FormFields(strBookmark).DropDown.Value = 1) Then
MsgBox ("Please select a " & Replace(Selection.FormFields(strBookmark).Name, "_", " ") & ".")
Call GoBackToPrevious(.FormFields(strBookmark).Name)
End If
End With
End Sub
and
Sub GoBackToPrevious(strPreviousField)
10: If (bool_debug) Then MsgBox ("GoBacktoPrevious - 10: strPreviousField = " & strPreviousField)
ActiveDocument.Bookmarks(strPreviousField).Range.Fields(1).Result.Select
End Sub
But when I tab out of any of the form fields, the insertion point jumps to the next form field and not back to the one that I just tabbed out of.
I know from the debug code that GoBackToPrevious is being passed the name of the current form field, but MS Word advances to the next field regardless.
I'd really appreciate it if someone can tell me how make MS Word return to and select the drop-down the user did not select appropriately instead of jumping to and selecting the next form field in the document.
Thank you.
P James Norris
EDIT:
Based on #TimothyRylatt comments, I have modified my macro and when they're called.
I have edited Validate as above (commenting out the Dim the strBookmark assignment, and I call it "on entry" to the next form field.
strBookmark is Dimed on the module's declaration section:
Option Explicit
Const bool_debug As Boolean = True
Const str_password As String = "###" ' I have a different password
Public strBookmark As String
and "on exit" from the "current" form field, I attempt to store the "current" bookmark name:
Sub StoreBookmark()
strBookmark = Selection.Bookmarks(1).Name
10: If (bool_debug) Then MsgBox ("StoreBookmark() - 10: strBookmark = " & strBookmark)
End Sub
which I call from the current form field "on exit".
But when I tab out of the current form field to the next form field, the insertion point doesn't go back to the "current" but instead stays in the next form field.
Anyone have any other suggestions/insights?
Thanks,
P James Norris

Highlight field background in continuous form

I have an Access continuous form. I would like to change the forecolor of a specific record's field.
I have the field to highlight from the FieldModified field. So for example FieldModified = "Converted". Converted being a field on my form.
I would like to change the color of the "Converted" field, and do this for each record in the form.
I thought this code would work, but I get an error on Me.[FieldModified].ForeColor. And I need to do this for each record in the form.
Code:
Private Sub Form_Load()
Dim fldName As String
fldName = Me.FieldModified.value
If (Not IsNull(fldName)) Then
Me.[fldName].ForeColor = vbRed '<--doesn't recognize fldName value
End If
End Sub
Updated code but it gives me an error 438 saying object doesn't support this property or method. But the form does highlight fields on the form but it highlights more then the one field "fldName"
Private Sub Form_Load()
Dim rstForm As String
Dim fldName As String
Set rstForm = Me.ChangedData.Form.Recordset
Do While Not rstForm.EOF
fldName = Me.FieldModified.value
If (Not IsNull(fldName)) Then
Me.Controls(fldName).ForeColor = vbRed '<--doesn't recognize fldName value
End If
rstForm.MoveNext
Loop
End Sub
You set the default format for the control. Every copy of the control in the continuous form uses this format. To format by a condition (fldName = Me.FieldModified.value) you need Condtional Formatting as Andre told you or use the detail-sections paint event (see update on bottom)
In conditional format wizard, you can create a condtion withExpression Isand[Converted].Name = [FieldModified]for each control of the form that should be highlighted, if its name matchesFiledModified. In Ms Access expressions you can't useMe, just omit it .
You can use VBA to format all controls with FormatConditions by code. If you want to modify an existing condition use.Modifyinstead of.Add
Private Sub Form_Load()
Dim ctl As Access.Control
For Each ctl In Me.Controls ' loop through all controls of form
On Error Resume Next ' Not all controls can have conditional format (e.g. labels). To save the check of control type, we ignore errors here
ctl.FormatConditions.Add(acExpression, , ctl.Name & ".Name=[FieldModified]").BackColor = vbRed 'add o format condition to control if possible, else an error is raised but ignored
If Err.Number Then 'show errors
Debug.Print "Error: " & Err.Number & " - " & Err.description & " in Control: " & ctl.Name & " Type is " & TypeName(ctl)
Err.Clear 'reset error to catch next
Else
Debug.Print "FormatCondition added to Control: " & ctl.Name & " Type is " & TypeName(ctl)
End If
Next ctl
On Error GoTo 0 ' turn on errors again, maybe add an error handler (On Error Goto MyErrHandler)
End Sub
Update:
You can use theDetails_Paintevent of the form to format same control different per record. This enables conditional format for controls withoutFormatConditionsproperty like labels, buttons.
Private Sub Detail_Paint()
Dim c As Access.Control
For Each c In Me.Detail.Controls
If c.Name = Me.FieldModified.Value Then
c.ForeColor = vbRed
Else
c.ForeColor = vbBlack
End If
Next
End Sub
You can't use a String variable like this, fldName is an identifier holding a String value.. not an identifier - in Me.ControlName, both Me and ControlName are identifiers.
But not all hope is lost! You can use a String to pull a Control object from a form!
All form controls should exist in the form's Controls collection, keyed by name:
Me.Controls(fldName).ForeColor = vbRed

VBA: userform multipage template

I'm making a Userform that would allow the user to changes the bounds on several charts at once. I figured out how everything should look on the first multipage, and now I'm wondering if there's any way I could add 11 pages at once to look just like the first page. My userform appears below.
I am still in the design phase for this. If there's a way to do this in the design that would be great. If there's a way to do in the Initialize sub that would also be great.
Based on your intended usage, you should be using a TabStrip instead of MultiPage being most controls within are the same layout (same amount of controls). MultiPage is intended for categorizing data with different controls on each page.
Consider this simple userform to demostrate the benefit of using TabStrip here:
The left side square is a Picture holder I have not put codes for.
With below code to handle tab changes, certain elements in the userform will change when a different Tab is clicked.
Option Explicit
Private Sub TabStrip1_Change()
Dim TabX As String
With Me.TabStrip1
TabX = .Tabs(.Value).Caption
Debug.Print "ActiveTab:", TabX
End With
Me.Frame1.Caption = "Maximum Bounds (" & TabX & ")"
Me.Frame2.Caption = "Minimum Bounds (" & TabX & ")"
Me.TextBox1.Value = "TextBox2 for " & TabX ' Forgot to change this Value to TextBox1 before the screenshot...
Me.TextBox2.Value = "TextBox2 for " & TabX
End Sub
Upon launching the userform (without setting UserForm_Initialize):
Tab2 clicked:
Tab1 clicked:

Outlook VBA Script Moving Text From Custom Form to Message Body

I have never used Outlook VBA (2010), but my manager tasked me to create a user form that sends IT requests and IS requests. I have the custom form created, where I gather all my text fields and print the text to a single text box.
This action is all defined within Sub CommandButton1_Click(), which ends with Send(). Within the sub, I have something like this for all text boxes:
Set Sj =Item.GetInspector.ModifiedFormPages("P.2").Controls("Subject_Text")
Set YNbox = Item.GetInspector.ModifiedFormPages("P.2").Controls("YNBox")
Set Rbox = Item.GetInspector.ModifiedFormPages("P.2").Controls("ReasonBox")
What I want to know is how do I take the texts within "P.2" and paste it into the Message area of "Message" Page?
Here is the code snippet for the printing out to a single text box:
FinalBox.Text = "Subject: " & Sj.Text & vbCrLf & _
vbCrLf & "Can work around the issue?: " & YNbox.Text & _
vbCrLf & "Reason For Ticketing: " & Rbox.Text & _
vbCrLf & "Department: " & Dbox.Text & _
vbCrLf & "Impact: " & Ibox.Text & _
vbCrLf & "Urgency: " & Ubox.Text & _
vbCrLf & "System/Machine Number: " & Mbox.Text & _
vbCrLf & "Was trying to accomplish: " & Abox.Text & _
vbCrLf & "Has it occured before?: " & Bbox.Text & _
vbCrLf & "First Noticed: " & Tbox.Text & _
vbCrLf & "Others affected by the issue: " & Affbox.Text & _
vbCrLf & "Additonal Comments: " & Addbox.Text
So, how do I take this and append it to the actual message field in Message page?
.
Thank you very much!!
P.S. I've been having issues with MailItem.body and whenever I create an object, for example:
Dim objMsg As Object,
I get an error that says "Expected end of statement"... I understand VB and VBA is different, but I didn't think it'd be giving me this much headache.
Edit:
Hello dbMitch and Tony Dallimore, thanks for helping me clarify my questions. Like I mentioned, I am a mere beginner when it comes to VBA, and I Just wanted to
`Sub Commandbutton
Set Sj = Item.GetInspector.ModifiedFormPages("P.2").Controls("Subject_Text")
Set YNbox = Item.GetInspector.ModifiedFormPages("P.2").Controls("YNBox")
Set Rbox = Item.GetInspector.ModifiedFormPages("P.2").Controls("ReasonBox")
Set Dbox = Item.GetInspector.ModifiedFormPages("P.2").Controls("DepartmentDropbox")
Set Mbox = Item.GetInspector.ModifiedFormPages("P.2").Controls("MachineBox")
Set Ibox = Item.GetInspector.ModifiedFormPages("P.2").Controls("ImpactBox")
Set Ubox = Item.GetInspector.ModifiedFormPages("P.2").Controls("UrgencyBox")
Set Abox = Item.GetInspector.ModifiedFormPages("P.2").Controls("AccomplishBox")
Set Bbox = Item.GetInspector.ModifiedFormPages("P.2").Controls("BeforeText")
Set Tbox = Item.GetInspector.ModifiedFormPages("P.2").Controls("Timebox")
Set Affbox = Item.GetInspector.ModifiedFormPages("P.2").Controls("AffectedBox")
Set Addbox = Item.GetInspector.ModifiedFormPages("P.2").Controls("AdditionalBox")
Set Tbox8 = Item.GetInspector.ModifiedFormPages("P.2").Controls("TextBox8")
Set MESBOX = Item.GetInspector.ModifiedFormPages("Message").Controls("Message")
Tbox8.Text = "Subject: " & Sj.Text & vbCrLf & _
vbCrLf & "Can work around the issue?: " & YNbox.Text & _
vbCrLf & "Reason For Ticketing: " & Rbox.Text & _
vbCrLf & "Department: " & Dbox.Text & _
vbCrLf & "Impact: " & Ibox.Text & _
vbCrLf & "Urgency: " & Ubox.Text & _
vbCrLf & "System/Machine Number: " & Mbox.Text & _
vbCrLf & "Was trying to accomplish: " & Abox.Text & _
vbCrLf & "Has it occured before?: " & Bbox.Text & _
vbCrLf & "First Noticed: " & Tbox.Text & _
vbCrLf & "Others affected by the issue: " & Affbox.Text & _
vbCrLf & "Additonal Comments: " & Addbox.Text
Send
End Sub
`
Sub I found online that is suppose to take an item and append the text onto message body. There seems to be an error every time I try to declare the object's type (Ex. ____ As _____). I was not sure how to modify this to make it fit with my code, but the error is thrown at Dim objItem As Object that says
Expected end of statement
Sub TestAppendText()
Dim objItem As Object
Dim thisMail As Outlook.MailItem
'On Error Resume Next
Set objItem = Application.ActiveExplorer.Selection(1)
If Not objItem Is Nothing Then
If objItem.Class = olMail Then
Set thisMail = objItem
Call AppendTextToMessage(thisMail, "Some text added at " & Now())
End If
End If
Set objItem = Nothing
Set thisMail = Nothing
End Sub
Sub AppendTextToMessage(ByVal objMail As Outlook.MailItem, ByVal strText As String)
Dim objCDO As MAPI.Session
Dim objMsg As MAPI.Message
Dim objField As MAPI.Field
Set objCDO = CreateObject("MAPI.Session")
objCDO.Logon "", "", False, False
If Not objMail.EntryID = "" Then
Set objMsg = objCDO.GetMessage(objMail.EntryID, _
objMail.Parent.StoreID)
objMsg.Text = objMsg.Text & vbCrLf & strText
objMsg.Update True, True
Set objField = objMsg.Fields(CdoPR_RTF_COMPRESSED)
If Not objField Is Nothing Then
objField.Delete
objMsg.Update True, True
End If
Set objField = Nothing
Set objField = objMsg.Fields(CdoPR_RTF_SYNC_BODY_COUNT)
If Not objField Is Nothing Then
objField.Delete
objMsg.Update True, True
End If
Else
strMsg = "You must save the item before you add text. " & _
"Do you want to save the item now?"
intAns = MsgBox(strMsg, vbYesNo + vbDefaultButton1, "Append Text to Message")
If intAns = vbYes Then
Call AppendTextToMessage(objMail, strText)
Else
Exit Sub
End If
End If
Set objMsg = Nothing
objCDO.Logoff
Set objCDO = Nothing
End Sub
I've also tried using a CDO object, but it gives me an error that says
ActiveX component can't create object: 'CDONTS.NewMail'
Set Item1 = Item.MessageClass
Set objCDONTS = CreateObject ("CDONTS.NewMail")
objCDONTS.Body = Tbox8.Text
Item1.Message = "Hi"
I apologize if this seems very simple to others.. I just have 0 experience with VBA/VBScript and Outlook designs. That's why I'm here, to learn!
Please do not ask a question like this again. I do understand the difficulty of telling one’s manager that you lack the background to tackle a task. The typical response seems to be: “It is easy: just look it up on the internet.” In one sense this is true. There is nothing in the answer below that you could not find in other answers. What you lack is the background to identify the features you require and to fit them together to create the solution. VBA is not a difficult language but it has many significant differences from other languages that will confuse an experienced programmer new to VBA. The Outlook Object model takes time to master.
There are many online Excel VBA and Outlook VBA tutorials. I think the Excel VBA tutorials are better. If you are asked to perform a similar task again, you must insist on having the time to study first. These answers of mine might help:
Update excel sheet based on outlook mail
How to copy Outlook mail message into excel using VBA or Macros
I wanted to create a complete solution since I did not believe another snippet would help. You need: “This works. Adjust it step by step to your exact requirement.”
I am not familiar with custom forms and can find nothing that says what advantage they offer over user forms which work with all versions of VBA. I did not want to take the time to study custom forms particularly as I have code for user forms that I can easily adjust to your requirement. If your custom form is working to your satisfaction, replace that part of my solution.
There are five parts to my solution:
The user form.
The first part of the subroutine SendTicket() which loads the user form and calls it to get data from the user.
The subroutine UserForm_Initialize() within the user form’s code which builds the form from parameters supplied by SendTicket().
The subroutine CommandButton1_Click() which performs minimal validation of the user’s data and stores it for SendTicket().
The second part of the subroutine SendTicket() which builds the email from the user’s data and sends it to the IT department.
1. The user form
I inserted a new user form, adjusted its size and added controls. If you do not know how to do this then look at one of the tutorials that introduce user forms.
If I add a label control to a user form and name it X, I can, for example:
Move it by changing X.Top.
Display some text by changing X.Caption.
The user form includes a Collection named Controls. A collection is what most languages call an unsorted list. Within Controls there will be an entry for every control (label, text box, command button, etc.) on the form. If the label X is the first control on the user form, I can access its properties as Controls(0).Top and Controls(0).Caption. This means I can have code specific to label X that reference it by name or I can have general code that handles all or selected labels by their position within Controls. For your requirement, I believed general code would be easier so that is what I have provided.
I created a label control and a text box control. I left the default names but changed some properties:
LABEL TEXT BOX
* Name Label1 TextBox1
Caption Prompt/Name
Font Tahoma 10 Tahoma 10
Height 12 18
Left 12 230
* Multiline True
* Scrollbars 2 - frmScrollBarsVertical
TextAlign 3 – frmTextAlighRight 1 – frmTextAlignLegt
Text/Value abcdefghijklmnopqrstuvwyz
* Visible False False
Width 200 400
* Word wrap True True
Properties starting “*” are important. The others are because I like the way they affect the form’s appearance.
In the UK, “Label1” and “TextBox1” are the default names for the first label and textbox. With Excel, default names vary with the local language; I do not know if this is true for Outlook. Within the code, it tells you how to change the default names if necessary.
My code assumes the captions for the labels will fit on a single line but the text entered into the text boxes may require several lines.
Having created my standard label and text box, I selected them, copied them, pasted them and then moved the copies so they were exactly under the first pair. I repeated this with the four controls then the eight controls and finally the sixteen controls. I ended with a column of sixteen labels and a column of sixteen text boxes. I was not concerned with the vertical position of the controls; I handle that later. If either column is not perfectly aligned, you can select a column and set the Left property for the entire group. I have created forms with hundreds of controls with acceptable performance so add more if you wish.
I created a command button. I lined it up with the text boxes but made the font larger. I retained the default name and caption.
By creating the command button last, the controls are in the correct tab order. The form opens with the cursor in the first (top) field and each tab takes the cursor to the next field and then to the button.
Finally, I set the width of the form so it was a little wider than the controls. I set the height so it was close to the screen height which on my laptop is about 560. It is possible to get the screen height from the system but that is beyond the scope of this answer. I set the caption to “Report issue”. I named it P2 which the closest I can get to your name (P.2 is an invalid name for a user form). The result was:
** 2. Part 1 of subroutine SendTicket()**
A macro cannot directly send parameters to a user form or receive values back. It must use global variables. P2Params is the global I use to pass data to the user form and I use P2Values to pass data back.
P2Params = Array("Subject", …) is the statement that loads P2Paramswith parameters. The first three parameters are "Subject", 18, True which specify the first text box. The prompt/name is “Subject”, the height is 18 and it is mandatory. Each further set of three parameters defines another text box.
I could have defined all this information within the form but getting a form like this looking the way you want can be very fussy particularly if you change your mind about the height of a text box so all the lower ones have to be moved down. With this approach you can change a text box’s height or change the sequence or add a new field with no hassle at all. Note: height defines the height allocated to the control. On my laptop and with my choice of font, 54 is enough for four lines. If the user types a fifth line, the scroll bars will appear against the relevant control so the user can see all the lines. You specify height of each text box based on some average or typical ticket but it does not matter if the user wants to enter more text than you expected.
Load P2 loads the form into memory and calls UserForm_Initialize() to initialise the form. .Show vbModal passes control to the form. Control is not returned until the user does something to return control. In this case, clicking the command button returns control providing the entered values pass the validation code.
3. The subroutine UserForm_Initialize()
I do not intend to say too much about this sub-routine. Comments within the code fully explain what the code does and the image below shows the result:
If you look down the parameters in P2Params. You can see where this layout came from. The beauty of this approach is that with a different set of parameters, a very different form can be produced. A requirement to import a list of text values is not uncommon so I have used variations of this code before and will again.
4. The subroutine CommandButton1_Click()
The user can enter values into the text boxes in required. Once they are correct, the user clicks the command button which was been re-captioned “Send” by the first part of subroutine SendTicket().
This routine validates that all mandatory fields have a value. I have implemented permitted ranges and other validation but this is sufficient for your requirement. If the field values are acceptable, the routine loads the entered values into array P2Values. As I said, only by storing values in a global variable can a user form return values to the caller.
5. The second part of the subroutine SendTicket()
This code takes the values from P2Values builds the email and sends it. I have send emails to an experimental Gmail account. You will need to replace the recipient with the address of your IT Department.
Summary
There is a lot here for you to think about. Work through it slower and come back with questions if necessary
SendTicket()
Option Explicit
Public Type FieldDtl
CtrlLabel As Long
CtrlTextBox As Long
Height As Long
Mandatory As Boolean
Prompt As String
End Type
Public P2Params As Variant
Public P2Values() As String
Sub SendTicket()
Dim InxFld As Long
Dim InxPrm As Long
Dim MailItemCrnt As MailItem
P2Params = Array("Subject", 18, True, _
"Can you work around the issue?", 18, True, _
"Reason For Ticketing", 30, True, _
"Department", 18, False, _
"Impact", 18, True, _
"Urgency", 18, True, _
"System/Machine Number", 18, True, _
"Was trying to accomplish", 54, True, _
"Has it occured before?", 18, True, _
"First Noticed", 18, False, _
"Others affected by the issue", 42, True, _
"Additional Comments", 54, True)
' Used to test total height of control exceeding height of screen
'P2Params = Array("Subject", 50, True, _
' "Can you work around the issue?", 50, True, _
' "Reason For Ticketing", 50, True, _
' "Department", 50, False, _
' "Impact", 50, True, _
' "Urgency", 50, True, _
' "System/Machine Number", 50, True, _
' "Was trying to accomplish", 54, True, _
' "Has it occured before?", 50, True, _
' "First Noticed", 50, False, _
' "Others affected by the issue", 54, True, _
' "Additional Comments", 54, True)
Load P2
With P2
.CommandButton1.Caption = "Send"
.Show vbModal
End With
' The bounds of P2Values are 1 to number of fields
' The bounds of P2Params could be 1 to NumberOfFields*3 but is almost
' certainly 0 to NumberOfFields*3-1
Set MailItemCrnt = CreateItem(olMailItem)
With MailItemCrnt
.BodyFormat = olFormatPlain
.Recipients.Add "AbbeyRuins33#gmail.com"
.Subject = P2Values(1) ' Assumes subject is first field
.Body = P2Params(LBound(P2Params) + 3) & ": " & P2Values(2)
InxFld = 3
For InxPrm = LBound(P2Params) + 6 To UBound(P2Params) Step 3
.Body = .Body & vbCrLf & P2Params(InxPrm) & ": " & P2Values(InxFld)
InxFld = InxFld + 1
Next
.Display
' .Send
End With
Set MailItemCrnt = Nothing
End Sub
Code for user form
Option Explicit
' In UK, the default name for a label is "LabelN" and the default name for a text box
' is "TextBoxN". In case the default name is different is non-English speaking
' countries, I use constants for these values. Change the value of these constants
' as necessary.
Const NameLabel As String = "Label"
Const NameTextBox As String = "TextBox"
' This code assumes there are N labels named NameLabel & 1 to NameLabel & N and
' N text boxes named NameTextBox & 1 to NameTextBox & N. NameLabelX is used to
' label TextBoxX which is used to obtain the Xth value from the user.
' User type FieldDtl is defined in the SendTicket module
Dim Fields() As FieldDtl
Private Sub CommandButton1_Click()
Dim ErrMsg As String
Dim InxFld As Long
' Check values have been entered for mandatory fields
ErrMsg = ""
For InxFld = 1 To UBound(Fields)
If Fields(InxFld).Mandatory And Controls(Fields(InxFld).CtrlTextBox).Text = "" Then
If ErrMsg <> "" Then
ErrMsg = ErrMsg & vbLf
End If
ErrMsg = ErrMsg & "Please enter a value for " & Fields(InxFld).Prompt
End If
Next
' No value entered for one or more mandatory fields
If ErrMsg <> "" Then
Call MsgBox(ErrMsg, vbOKOnly)
Exit Sub
End If
' Save values for caller
ReDim P2Values(1 To UBound(Fields))
For InxFld = 1 To UBound(Fields)
P2Values(InxFld) = Controls(Fields(InxFld).CtrlTextBox).Text
Next
Unload Me
End Sub
Private Sub UserForm_Initialize()
Const GapBetweenCtrls As Long = 5
Dim InxCtrl As Long
Dim InxFld As Long
Dim InxPrm As Long
Dim NumFields As Long
Dim NumParams As Long
Dim TopNext As Long
' Note: LBound(P2Params) can be zero or one but will almost certainly be zero.
' This code allows for either possibility.
NumParams = UBound(P2Params) - LBound(P2Params) + 1
Debug.Assert NumParams Mod 3 = 0
NumFields = NumParams / 3
ReDim Fields(1 To NumFields)
' Import values from P2Params
' P2Params must contain 3N paramerers where N is the number of values
' to be obtained from the user. The three values are:
' Prompt/Name for value.
' Height of value (so control can be sized for multi-line values).
' Mandatory? (True is a value must be entered)
InxFld = 1
For InxPrm = LBound(P2Params) To UBound(P2Params) Step 3
Fields(InxFld).Prompt = P2Params(InxPrm)
Fields(InxFld).Height = P2Params(InxPrm + 1)
Fields(InxFld).Mandatory = P2Params(InxPrm + 2)
InxFld = InxFld + 1
Next
' Controls can be accessed by name (for example Label1.Caption) or
' by position within the collection Controls (for example
' Controls(1).Caption). Add control numbers to Fields().
For InxCtrl = 0 To Controls.Count - 1
If Left$(Controls(InxCtrl).Name, Len(NameLabel)) = NameLabel Then
' Extract number at end of name
InxFld = CLng(Mid(Controls(InxCtrl).Name, Len(NameLabel) + 1))
If InxFld <= NumFields Then
' This control will be used
Fields(InxFld).CtrlLabel = InxCtrl
End If
ElseIf Left$(Controls(InxCtrl).Name, Len(NameTextBox)) = NameTextBox Then
InxFld = CLng(Mid(Controls(InxCtrl).Name, Len(NameTextBox) + 1))
If InxFld <= NumFields Then
' This control will be used
Fields(InxFld).CtrlTextBox = InxCtrl
End If
End If
Next
' For InxFld = 1 To NumFields
' Debug.Print Fields(InxFld).Name & " " & Fields(InxFld).Height & " " & _
' Fields(InxFld).Mandatory & " " & Fields(InxFld).CtrlLabel & _
' " " & Fields(InxFld).CtrlTextBox
' Next
' Now have information necessary to build form.
' This code assumes/relies on:
' * All properties of the textbox controls being correct
' except for Top and Height.
' * All properties of the label controls being correct except for Top.
' * The Height of the label controls being less than the Height of any
' Textbox control.
' * The Visible property of the label and textbox controls being false.
' * The Multiline property of the textbox controls being true
' * The Scrollbars property of the textbox controls being
' 2 = frmScrollBarsVertical
' * The Width of the label property being such that all captions fit.
TopNext = GapBetweenCtrls
For InxFld = 1 To NumFields
With Controls(Fields(InxFld).CtrlLabel)
.Top = TopNext
.Caption = Fields(InxFld).Prompt
.Visible = True
End With
With Controls(Fields(InxFld).CtrlTextBox)
.Top = TopNext
.Height = Fields(InxFld).Height
.Text = ""
.Visible = True
End With
TopNext = TopNext + Fields(InxFld).Height + GapBetweenCtrls
Next
With CommandButton1
.Top = TopNext
TopNext = TopNext + .Height + GapBetweenCtrls
End With
' Set scroll height so if total height of controls exceeds height
' of form, user can scroll from top to bottom.
ScrollHeight = TopNext
End Sub

Excel combo box problem

I have a form in Excel with a combo box control. I want the values to be filled from a database table when the combo box is opened using what has already been typed in as a LIKE criteria. This is the code I have so far for the DropButtonClick event to achieve this.
Private Sub cboVariety_DropButtonClick()
Static search_text As String
Static is_open As Boolean
Dim rs As New Recordset
If is_open Then
is_open = False
Exit Sub
End If
is_open = True
If search_text = cboVariety Then Exit Sub
search_text = cboVariety
cboVariety.Clear
cboVariety.AddItem search_text
If Len(search_text) > 2 Then
rs.Open _
"SELECT Name FROM tbl_Varieties " & _
"WHERE Name LIKE '%" & search_text & "%' " & _
"ORDER BY Name", connect_string, adOpenStatic
Do Until rs.EOF
If rs!Name <> search_text Then cboVariety.AddItem rs!Name
rs.MoveNext
Loop
rs.Close
End If
End Sub
The problem is that the DropButtonClick event fires both when the combo box is opened and when it is closed. If this sub executes when the combo box is closing, the code that clears the combo box causes the user's selection to be erased.
I'm trying to tell when the box is closed using the is_open variable, which alternates between true and false each time the event sub is executed. This seems like a brittle solution to the problem. Is there a better way?
You are on the right track by using the is_open boolean to track the state of the combo box, but what you really want to track is the state of "should I re-populate the combo box with database data?"
When do you want the list box populated? Currently, you want the list box to be populated every time the user clicks the drop-down box (not taking into account your is_open state variable). Is this really what you want?
I would imagine that what you really want is to have the combo box only update after something else changes. Perhaps you only want the drop down list to update when the form first opens. Maybe you only want the data to change when the text in a search box changes. If this is the case, you need to base your logic on the state of when you actually want to perform the update.
For example, let's say you want to update the combo box only if the text in a search box changes. I'm not looking at Excel at the moment, but let's pretend you have a text box called txtSearch with a Text property. I'd start by adding a module or class level variable to maintain the state of the previous text entry:
Private mPreviousSearchText As String
Then I'd update my event code like so:
Private Sub cboVariety_DropButtonClick()
Dim rs As New Recordset
Dim search_text As String
search_text = txtSearch.Text
If mPreviousSearchText = search_text Then
'The current search matches the previous search,'
'so we do not need to perform the update.'
Exit Sub
End If
cboVariety.Clear
cboVariety.AddItem search_text
If Len(search_text) > 2 Then
rs.Open _
"SELECT Name FROM tbl_Varieties " & _
"WHERE Name LIKE '%" & search_text & "%' " & _
"ORDER BY Name", connect_string, adOpenStatic
Do Until rs.EOF
If rs!Name <> search_text Then cboVariety.AddItem rs!Name
rs.MoveNext
Loop
rs.Close
End If
'Set the previousSearchText var to be the search_text so that it does'
'not run unless the value of my text box changes.'
mPreviousSearchText = search_text
End Sub
The entire point is to establish when you actually want to perform the update and find out a way to tie your logic decision to the state associated with when you want to perform the action, which is only coincidentally related to the user clicking on the drop-down box.
I found a simple way to solve this. It doesn't seem like it should work, but if I just reassign the value of the combo box after rebuilding the list, it doesn't discard the value that is selected.
Private Sub cboVariety_DropButtonClick()
Static search_text As String
Dim rs As New Recordset
If search_text = cboVariety Then Exit Sub
search_text = cboVariety
cboVariety.Clear
If Len(search_text) > 2 Then
rs.Open _
"SELECT Name FROM tbl_Varieties " & _
"WHERE Name LIKE '%" & search_text & "%' " & _
"ORDER BY Name", connect_string, adOpenStatic
Do Until rs.EOF
cboVariety.AddItem rs!Name
rs.MoveNext
Loop
rs.Close
End If
'' Reassign cboVariety in case this event was triggered by combo close
cboVariety = search_text
End Sub
This worked for me, instead of assigning the value, i assign the ListIndex property.
index = cb.ListIndex
cb.Clear
while condition
cb.AddItem item
Wend
If index < cbLinia.ListCount Then
cb.ListIndex = index
Else
cb.ListIndex = -1
End If
Use GotFocus() instead.
Private Sub ComboBox1_GotFocus()
MsgBox "caca"
End Sub
Triggers only when the combo get focus.
HTH