VBA - Proceed Command with Enter - vba

I want to make this textbox: if I type "clean" and press enter, I want it to take action like below. Is there any ways to achieve it? Here's what I tried.
Private Sub TextBox1_Change()
If TextBox1.Text = "clean" + KeyCode(13) Then
Shell "cmd /c cleanmgr.exe", vbHide
End If
End Sub
Thanks.

This is possibly what you are looking for:
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
If TextBox1.Text = "clean" Then
MsgBox "ok" 'for test
'do your stuff here!!
End If
End If
End Sub

Related

Passing MSForms.Control as argument in Word VBA

I have to set ActiveX control tab order in MS Word using VBA. So here is the basic code:
Private Sub radioFull_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
If KeyCode = 9 Then
radioIntern.Activate
End If
End Sub
Problem is I have an active Restrict Editing Protection on the document set by password. Thus after starting protection, while pressing a tab on any control, it deny to functioning saying that I have a protection on the document.
So, during execution of the above function, I first have to un-protect the document, moving tab to next field and then re-protect by the following function:
Private Sub ToggleProtect()
If ActiveDocument.ProtectionType <> wdNoProtection Then
ActiveDocument.Unprotect Password:="password"
Else
ActiveDocument.Protect Password:="password", NoReset:=True, _
Type:=wdAllowOnlyFormFields, _
UseIRM:=False, EnforceStyleLock:=False
End If
End Sub
Private Sub radioFull_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
If KeyCode = 9 Then
ToggleProtect
radioIntern.Activate
ToggleProtect
End If
End Sub
It works well. So I intend to shorten the main code a little bit more by something like this:
Private Sub radioFull_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
tabOrder(KeyCode, controlName)
End Sub
and the tabOrder function in this case like the follwoing:
Public Sub tabOrder(K as integer,t as string)
If KeyCode = K Then
ToggleProtect
t.Activate
ToggleProtect
End If
End Sub
But I am not familiar on VBA function argument. So please tell me how to pass the argument or write the function correctly so that I can maintain tab order in MS Word form?
Even though the MS Forms controls are derived from MSForms.Control VBA is apparently unable to "cast" them to this data type. It can work with the general type, however. The trick is to declare the procedure argument as data type Variant.
While I was at it, I made another small optimization to the code by declaring an object variable of type Word.Document for passing the document to ToggleProtect. While it's unlikely, it is theoretically possible that the user will change documents during code execution, making the ActiveDocument a different one than that which triggered the code. So if you get the target document immediately then the code will always execute on the correct document, no matter which one currently has the focus.
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
Dim doc As Word.Document
Set doc = Me
tabOrder KeyCode, doc, Me.TextBox1
End Sub
Public Sub tabOrder(ByVal KeyCode As MSForms.ReturnInteger, _
ByRef doc As Word.Document, ByRef t As Variant)
If KeyCode = 9 Then
ToggleProtect doc
t.Activate
ToggleProtect doc
End If
End Sub
Private Sub ToggleProtect(doc As Word.Document)
If doc.ProtectionType <> wdNoProtection Then
doc.Unprotect Password:="password"
Else
doc.Protect Password:="password", NoReset:=True, _
Type:=wdAllowOnlyFormFields, _
UseIRM:=False, EnforceStyleLock:=False
End If
End Sub
In your KeyDown event, it looks like you want to pass the KeyCode and the Control. Therefore, the arguments you pass must match the signature of the tabOrder sub. Look how KeyCode is defined and copy/paste to your tabOrder sub. The second argument will be defined as Control allowing for any control to be passed. Here is an example of what I am talking about:
Private Sub radioFull_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
tabOrder KeyCode, radioFull
End Sub
Public Sub tabOrder(ByVal KeyCode As MSForms.ReturnInteger, ByRef t As MSForms.Control)
If KeyCode = 9 Then
ToggleProtect
t.Activate
ToggleProtect
End If
End Sub

VBA - TextBox_Exit doesn't work properly when closing with ESC

I have a form with a TextBox1 and a CommandButton1.
The Cancel property of the CommandButton1 is True. So I can close the form with a key press on Esc.
The TextBox1 has an Exit event, so when leaving this element will fire an event. In this event I will print the user input and some static content.
Sub CommandButton1_Click()
Unload Me
End Sub
Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Debug.Print "Textbox1_Exit was fired, content was: " & TextBox1.Value
End Sub
Now I enter some content in the TextBox1, let's say I enter 'foo'.
If I close the form with the CommandButton1 the output will be:
TextBox1_Exit was fired, content was: foo
The problem:
If I leave the form via the Esc key, the output will only be:
TextBox1_Exit was fired, content was:
So only the static part of Debug.Print will be printed.
I would like to get the user input in both cases.
Okay so this was a bit tricky - since you can't grab the TextBox1.Value when using Esc from the Userform, you can use a Public string variable instead which mimics the entries made into the TextBox. So you'll need to declare a Public variable, add a TextBox_Change event, and add a Userform_Initialize event to reset the string each time:
Public mystring As String
Sub CommandButton1_Click()
Unload Me
End Sub
Private Sub TextBox1_Change()
If Not Len(TextBox1.Value) <= Len(mystring) + 1 Then
mystring = mystring & Right(TextBox1.Value, 1)
Else
If TextBox1.Value <> "" Then
mystring = TextBox1.Value
End If
End If
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Debug.Print "Textbox_Exit was fired, content was: " & mystring
End Sub
Private Sub UserForm_Initialize()
mystring = ""
End Sub
you could use UserForm_QueryClose event to catch the UserForm exit event and call TextBox1_Exit one:
Option Explicit
Sub CommandButton1_Click()
Unload Me
End Sub
Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Debug.Print "Textbox1_Exit was fired, content was: " & TextBox1.Value
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Dim myVar As MSForms.ReturnBoolean
Me.TextBox1_Exit myVar
End Sub

VBA SetFocus on Keydown not working if checkbox true?

I have the following form in excel. It is part of a simple inventory worksheet, and is used to update the status of items. It was functioning as intended, however when I tried to add in a checkbox to make the selected status persist (allowing me to only type in the serial rather than serial and status every time when working with a batch of items) I noticed that the focus after submitting cycles forward as if I pressed tab rather than being where I set it with SetFocus.
I'm presuming this is an oversight related to either the event cycle for KeyDown or nested If/Else logic, but I've had no luck actually diagnosing it. I've only recently started using VBA, and there are a lot of quirks I'm trying to understand.
Private Sub clear()
Me.txtSerial = ""
If cbPersist.Object.Value = False Then
Me.cboxStatus = ""
Me.cboxStatus.SetFocus
Else
Me.txtSerial.SetFocus
End If
End Sub
Private Sub submit()
Dim loc As Range
Dim ws As Worksheet
Set ws = Worksheets("Full Inventory")
Set loc = ws.Columns("B").Find(what:=Me.txtSerial.Value, LookIn:=xlValues, lookat:=xlWhole)
If Not loc Is Nothing Then
ActiveWindow.ScrollRow = loc.Row
ws.Cells(loc.Row, 10).Value = Me.cboxStatus.Value
Else
MsgBox "Serial not found."
End If
clear
End Sub
Private Sub txtSerial_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyReturn Then
submit
ElseIf KeyCode = vbKeyEscape Then
clear
End If
End Sub
Private Sub UserForm_Initialize()
cboxStatus.List = Array("Stock", "Shipped", "Research", "Sent Back", "Return")
End Sub
Suggest the following:
Code snippet of UserForm module
Private Sub txtSerial_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = vbKeyReturn Then
submit
KeyCode = vbKeyPageDown ' << modify Enter key value to prevent from tab hopping
ElseIf KeyCode = vbKeyEscape Then
clear
End If
End Sub

push enter key in text boxt then go to specific cell

How to move cursor in text box with enter in text box?
Here is my code, it gives me a syntax error.
Private Sub TextBox2_Change()
Sheets("30").Range("D18") = TextBox2.Value
TextBox2.Enter Then Sheets("30").Range("E19").Select
End Sub
Instead of using the Change event, use the KeyUp event and check for the KeyCode vbKeyReturn:
Private Sub TextBox2_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = KeyCodeConstants.vbKeyReturn Then
Sheets("30").Range("E19").Select
End If
End Sub

How to detect if a specific key was pressed?

I'm wondering is there a way to detect if a specific key (like backspace) was pressed. This is what I'm shooting for:
Private Sub SomeTextBox_Change()
If len(Me.SomeTextBox.Value) = 3 and KEYPRESSED is NOT BACKSPACE Then
<.......Code Here>
Else
<.......Code Here>
End if
End Sub
You should use KeyPress event instead of Change event:
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If Len(Me.SomeTextBox.Value) = 3 And KeyAscii <> 8 Then 'Backspace has keycode = 8.
<.......Code Here>
Else
<.......Code Here>
End If
End Sub
Full list of keycodes you can find here: http://www.asciitable.com/
This example assigns "InsertProc" to the key sequence CTRL+PLUS SIGN and assigns "SpecialPrintProc" to the key sequence SHIFT+CTRL+RIGHT ARROW.
Application.OnKey "^{+}", "InsertProc"
Application.OnKey "+^{RIGHT}","SpecialPrintProc"
for more examples and infos go on : https://msdn.microsoft.com/en-us/library/office/aa195807%28v=office.11%29.aspx
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode.Value = vbKeyF1 Then
MsgBox "F1 is pressed"
End If
End Sub
You should use KeyPress event instead :
Private Sub SomeTextBox_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If Len(Me.SomeTextBox.Value) = 3 And KeyAscii <> vbKeyBack Then
'<.......Code Here>
Else
'<.......Code Here>
End If
End Sub
And you can use KeyAscii = 0 to cancel the key that was entered!
Find a list of all Ascii values here http://www.asciitable.com/