Textbox on Access form passing previous value - vba

I created a search form.
There is a text box for the search text. The user triggers the search event by either clicking on the search button or pressing the enter key.
The button click event is working.
On pressing of enter key for the first time the text box is passing the value which was entered in the text box from the previous event. If I press the enter key a second time the current value is passed.
For instance on the form load the text box is empty then I enter the search text as "Ali" and press enter key then the value "NULL" is passed and once again I press enter key then the value "Ali" is passed.
Option Compare Database
Option Explicit
Private Sub btnSearch_Click()
Dim SQL, strSearch As String
strSearch = Nz(Me.txtSearch.Value, "")
SQL = "SELECT tbl_mst_Employee_Details.emp_ID, " _
& "tbl_mst_Employee_Details.emp_Name " _
& "FROM tbl_mst_Employee_Details " _
& "where [emp_Name] like '*" & strSearch & "*' " _
& "ORDER BY tbl_mst_Employee_Details.emp_Name;"
Me.lstEmployee.RowSource = SQL
Me.lstEmployee.Requery
Me.txtEmpID.Value = ""
Me.txtEmpName.Value = ""
Me.Refresh
End Sub
Private Sub Form_Load()
Me.txtEmpID.Value = ""
Me.txtEmpName.Value = ""
Me.txtSearch.Value = ""
End Sub
Private Sub lstEmployee_Click()
With lstEmployee
Me.txtEmpID.Value = .Column(0)
Me.txtEmpName.Value = .Column(1)
End With
End Sub
Private Sub lstEmployee_DblClick(Cancel As Integer)
Forms!frmEmployeeShiftDetails.txtEmpID.Value = Me.txtEmpID
Forms!frmEmployeeShiftDetails.txtEmpName.Value = Me.txtEmpName
DoCmd.Close
Forms!frmEmployeeShiftDetails.txtEmpID.SetFocus
End Sub
Private Sub lstEmployee_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
lstEmployee_DblClick (0)
End If
End Sub
Private Sub txtSearch_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
btnSearch_Click
End If
End Sub

Simply set the focus to the search button first.
Additionally I would also check for pressing tab (and use constants for both, return and tab).
For having constant UI behaviour I would take care that the search button receives the focus when pressing tab in the search box, so set the correct tab order in the form.
Private Sub txtSearch_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyReturn Or KeyCode = vbKeyTab Then
btnSearch.SetFocus
btnSearch_Click
End If
End Sub

Related

How can i pass a variable from userform1 textfield dblclk event to userform2 and then dynamically pass data back to userform1 through cmdbutton click

On userform1 I have a text field that when it is doubleclicked opens a "timebox" Userform 2. The user then can adjust the time and then either cancel or apply. Apply should fill in Userform1 Textbox with the selection from Userform2.
If it was once instance no problem but i'm trying to use the Userform 2 on 28 + fields and can't reference each one separately. I need to pass the textfield.name on Userform1 to give Userform2 the address in which to send the data. But its userform2 cmdbuttom - Apply.
I looked at ByVal and ByRef which seems to work when its a Sub but not when its a cmdbutton.
Userform1 > Field
Public Sub AgStart1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Dim fieldname As String
fieldname = UserForm1.AgStart1.Name
TimeForm1.Show
End Sub
UserForm2
Public Sub TimeApply1_Click()
Dim timeselect
timeselect = Me.txt_Hours.Value & ":" & Me.txt_Mins & " " & Me.txt_AmPm
'I need the value above to be sent back to the field that spawned the Userform2
TimeForm1.Hide
End Sub
OR a better way like activecell for user form fields
Userform1 text field
Useform2 spawned from dblclk
Something like this should work:
UserForm1
Public Sub AgStart1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
PopTime AgStart1
End Sub
Public Sub AgStart2_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
PopTime AgStart2
End Sub
'etc etc
Sub PopTime(ctrl As Object)
Dim frm As New TimeForm1
Set frm.TheControl = ctrl 'pass the control to the second form
frm.Show
End Sub
UserForm2
Public TheControl As Object
Public Sub TimeApply1_Click()
'set the value of the passed control
TheControl.Value = Me.txt_Hours.Value & ":" & Me.txt_Mins & " " & Me.txt_AmPm
Me.Hide
End Sub

Handling / Performing / Managing tasks in Userform with the help of keyboard ( shortcut keys )

I have a User-form
For most of Check-Boxes/ Buttons I assigned a Key. Can be execute by pressing:
Alt + Assigned-key
I had googled the following code.
Private Sub UserForm_Initialize()
Me.PASTE.Accelerator = "V"
Me.CEEMEA.Accelerator = "C"
End Sub
Problem is I have to Press Alt key to perform any given task.
Q. Is there any short way of doing this without pressing AltKey?
My progress After Robin's Original-Answer
Firstly I set focus on Macros Button.
Private Sub UserForm_Initialize()
Me.Macros.SetFocus
End Sub
Then on Macro_Keydown Event I put the following code.
Private Sub Macros_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyB Then
Bulgaria.Value = Not Bulgaria.Value
ElseIf KeyCode = vbKeyE Then
Estonia.Value = Not Estonia.Value
ElseIf KeyCode = vbKeyH Then
Hungary.Value = Not Hungary.Value
ElseIf KeyCode = vbKeyA Then
Latvia.Value = Not Latvia.Value
ElseIf KeyCode = vbKeyL Then
Lithuania.Value = Not Lithuania.Value
ElseIf KeyCode = vbKeyM Then
Macedonia.Value = Not Macedonia.Value
ElseIf KeyCode = vbKeyP Then
Poland.Value = Not Poland.Value
ElseIf KeyCode = vbKeyR Then
Romania.Value = Not Romania.Value
ElseIf KeyCode = vbKeyU Then
Ukraine.Value = Not Ukraine.Value
End If
End Sub
Updated answer
The original answer didn't really meet the brief because whilst handling the UserForm events for e.g. KeyDown works for a form with no other controls, it doesn't work for a form with controls. This is because the event only works when the form has the focus. When the form has other controls, it never receives the focus. Also, it is not possible to set the focus onto the UserForm. Almost all forms will have some other controls, so the original answer is practically useless. So let's shamelessly adapt an idea from Andy Pope on MSDN to meet the OP's requirements.
First, insert a VBA Class into the project with this code:
Public WithEvents m_objGroupCheckBox As MSForms.CheckBox
Private Sub m_objGroupCheckBox_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
MsgBox "Keypress was: " & Chr(KeyCode) & " on " & m_objGroupCheckBox.Caption
Select Case Chr(KeyCode)
Case 1:
UserForm1.CheckBox1.Value = Not UserForm1.CheckBox1.Value
Case 2:
UserForm1.CheckBox2.Value = Not UserForm1.CheckBox2.Value
Case "3"
UserForm1.CheckBox3.Value = Not UserForm1.CheckBox3.Value
End Select
End Sub
The Class defines a generic event handler for a CheckBox on the UserForm. For the purposes of this example, we will make key presses of 1, 2 and 3 toggle the checkbox state for the 3 CheckBoxs on the form.
Second, put the code in the Userform's initialize event. It creates a collection of this custom class that references back to the original checkboxes created on the UserForm.
Private m_colCheckBoxes As Collection
Private Sub UserForm_Initialize()
Dim lngIndex As Long
Dim objGroupCheckBox As clsGroupCheckBox
Set m_colCheckBoxes = New Collection
For lngIndex = 1 To 3
Set objGroupCheckBox = New clsGroupCheckBox
Set objGroupCheckBox.m_objGroupCheckBox = Me.Controls("CheckBox" & lngIndex)
m_colCheckBoxes.Add objGroupCheckBox, CStr(m_colCheckBoxes.Count + 1)
Next
End Sub
So now, if we have a UserForm in the designer like this, with each CheckBox named CheckBox1, CheckBox2 and CheckBox3:
Then, our generic event handler will allow us to define a single place to handle the KeyDown event and set CheckBox status in one spot.
Original answer - not as useful as it looks :(
You can directly handle the KeyDown event of the UserForm and enter your specific logic in there. Maybe you should check out KeyUp and KeyPress as well depending on how you think the form will work.
MSDN notes that '..."A" and "a" are returned as the same key. They have the identical keycode value. But note that "1" on the typewriter keys and "1" on the numeric keypad are returned as different keys, even though they generate the same character.' - MSDN Link
You can handle SHIFT, CTRL and ALT as well.
Private Sub UserForm_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode >= vbKeyA And KeyCode <= vbKeyZ Then
MsgBox "You pressed " & Chr(KeyCode)
ElseIf KeyCode >= vbKeyF1 And KeyCode <= vbKeyF12 Then
MsgBox "Function time!"
End If
End Sub
'VBA Shortcut Keys not work in UserForm [Partially Solved]
Public Sub CallSub() 'code must be in Module
'-do this code-
Private Sub Workbook_Activate() 'code must be in (ThisWorkbook)
Application.OnKey "^{f5}", "callSub"
'^ this code only work with Excel Worksheet not in Userform
Private Sub XxX_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) 'code must be in Userform with SHOWMODAL = False
If KeyCode = 17 Then AppActivate "microsoft excel"
'XxX means all CommandButton and Textbox and Listbox and Combobox
'Keycode 17 is Ctrl Key if you are using Ctrl+F5 - when you press Ctrl it will activate Excel Worksheet

Display of data in access report based on form selection

I have a check box on my access form. If the user selects that check box , one column in an access report should display the values in 1000's
How can this be done?
By passing the value of the checkbox into the OpenArgs when you run the report, you can set the format of the column. Here's what the report opening code might look like:
Private Sub cmdRun_Click()
Dim bFormatted As Boolean
bFormatted = chkFormat.Value
DoCmd.OpenReport "ReportName", acViewPreview, , , , bFormatted
End Sub
Then in the Open event of the Report:
Private Sub Report_Open(Cancel As Integer)
Dim sArgs As String
Dim bFormatted As Boolean
sArgs = OpenArgs & ""
If sArgs <> "" Then
bFormatted = CBool(sArgs)
End If
If bFormatted Then
txtBox.Format = "0000"
End If
End Sub
I have not checked the correct format. That's left up to you.

lock a line for editing in a textbox in VBA

I have a textbox on a userform. When the userform displays, the textbox opens with some
default value.
I want it to be such that the Line1 (or some words) of the default message is displayed in grey color and must be locked for editing. Is it possible?
Locking the TextBox for Editing?
Yes. it is possible.
Just set the .Locked Property to True
Locking/Coloring just the first line or part of a text in textBox?
No. It is not possible in VBA. For partial coloring, you may want to use RichTextBox in lieu of TextBox but then again you will not be able to partially lock the control.
Edit
Alternative: Since the first line of text contains text that shouldn't be edited then why not show that info in a ToolTip using the .ControlTipText property of the TextBox or say a Label which displays when you hover the mouse on top of the TextBox?
For example (Using the .ControlTipText property)
Option Explicit
'~~> This is what goes in the tooltip. Amend as applicable.
Const sMsg As String = "Hello World! This is an example of tooltip text"
Private Sub UserForm_Initialize()
Dim sSample As String
Dim i As Long
For i = 1 To 10
sSample = sSample & "Blah Blah" & i & vbNewLine
Next i
TextBox1.Text = sSample
'~~> Set to starting point
TextBox1.SelStart = 0
End Sub
Private Sub TextBox1_MouseMove(ByVal Button As Integer, _
ByVal Shift As Integer, _
ByVal X As Single, _
ByVal Y As Single)
TextBox1.ControlTipText = sMsg
End Sub
And now when you hover the text on top of the TextBox, you will be shown the ToolTip
This is more a workaround than a solution, but it works perfect (atleast on my computer).
Const defaultLine As String = "YourText" & vbcrlf
Private Sub TextBox1_Change()
Static oldValue As String
'set oldValue if empty
If oldValue = "" Then
oldValue = defaultLine
End If
'disable the change of the first line
If Left(TextBox1.Value, Len(defaultLine)) <> defaultLine Then
TextBox1.Value = oldValue
Else
oldValue = TextBox1.Value
End If
End Sub
Private Sub UserForm_Initialize()
TextBox1.Value = defaultLine
End Sub

Adding description into TextBoxes within an Excel VBA form that dissapears once user starts typing inside it

We have a userform with multiple textboxes and we would like to build something similar to the link image below, in terms of showing what the user should input in each text box:
http://d2o0t5hpnwv4c1.cloudfront.net/426_formsBestPractices/comments.png
The "default" text would disappear once the user starts typing (as opposed than once the user "lands" cursor within the textbox.
Also, if nothing gets entered within the textbox the default text would not be submitted and a blank would be used.
Can this be done?
Any suggestions will be greatly appreciated.
Can I ask why you want the default text to dissapear once a user changes the text and not once they enter the textbox?
This is not what most users will expect, I think it will be slightly confusing for some and wouldn't recommend it. The user will most likely try and delete the old text before typing their new text creating extra work.
I would use something like this:
Const sNameDefault As String = "Your Name Here"
Const sEmailDefault As String = "Your Email Here"
Private Sub UserForm_Initialize()
Me.TextBox1.Text = sNameDefault
Me.TextBox2.Text = sEmailDefault
CommandButton1.SetFocus
End Sub
'// TextBox1 - Name
Private Sub TextBox1_Enter()
With Me.TextBox1
If .Text = sNameDefault Then .Text = vbNullString
End With
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With Me.TextBox1
If .Text = vbNullString Then .Text = sNameDefault
End With
End Sub
'// TextBox2 - Email
Private Sub TextBox2_Enter()
With Me.TextBox2
If .Text = sEmailDefault Then .Text = vbNullString
End With
End Sub
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
With Me.TextBox2
If .Text = vbNullString Then .Text = sEmailDefault
End With
End Sub
Private Sub CommandButton1_Click()
Dim sName As String, sEmail As String
'// Get Name
If Me.TextBox1.Text = sNameDefault Then
sName = vbNullString
Else
sName = Me.TextBox1.Text
End If
'// Get Email
If Me.TextBox2.Text = sEmailDefault Then
sEmail = vbNullString
Else
sEmail = Me.TextBox2.Text
End If
MsgBox ("Your Name: " & sName & vbNewLine & " Your Email:" & sEmail)
Unload Me
End Sub
The above example is simply a userform with two textbox's and a commandbutton. Clicking inside the textbox will clear the default text. If the user enters nothing clicking another textbox or control will cause the default text to be added back. Once the command button is clicked the code will return blank if the default text remains.
Yes it is possible :)
I have created a sample for you. You can download it from here.
http://wikisend.com/download/143478/Sample.xlsm
The trick is to create 2 similar TextBoxes and hide the 'original' one behind the dummy TextBox ("Which has the default text")
When you start typing in the dummy, the text will actually be typed in the textbox which is hidden.
And when you are pulling values, simply pull the values from the 2nd text box so the default data is not considered :)
Hope this helps.
Code Used
Private Sub UserForm_Initialize()
TextBox1.SelStart = 0
TextBox1.SelLength = Len(TextBox1.Text)
End Sub
Private Sub CommandButton1_Click()
MsgBox TextBox2.Text
End Sub
Private Sub TextBox1_Change()
TextBox1.Visible = False
With TextBox2
.Text = Replace(TextBox1.Text, "Please enter your name", "")
.Visible = True
.SetFocus
.SelStart = Len(TextBox2.Text)
End With
End Sub