How to use a variable with a Property After - excel

This should be simple. I am working with userforms. I want to save a number that is stored in a cell and concatenate it with "lbl" and store it in a variable called Label. This works. I Then need to use the property .Caption but get a 424 error. Replacing the variable with what is stored in it ("lbl1"), the code runs.
Not sure why this is not working. Any help appreciated.
Sub ErrorExample()
Dim Label As String
'Clear previous click
If Worksheets("BackEnd").Range("D2").Value = "" Then
'No previous click
Else
'This does not work
Label = "lbl" & Worksheets("BackEnd").Range("D2").Value
With Label
'Clear previous click
.Caption = ""
End With
'This works
With lbl2
'Clear previous click
.Caption = ""
End With
End If
End Sub

Userform: Reference a Control By Its Name
Copy the code into the user form's module.
Private Sub ToClearOrNotToClear()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("BackEnd")
Dim Label As String: Label = CStr(ws.Range("D2").Value)
Dim lbl As Control
If Len(Label) > 0 Then
On Error Resume Next
Set lbl = Controls("lbl" & Label)
On Error GoTo 0
If lbl Is Nothing Then
MsgBox "Label not found!", vbCritical
Exit Sub
End If
If Len(CStr(lbl.Caption)) = 0 Then
MsgBox "Label is clear!", vbExclamation
Exit Sub
End If
lbl.Caption = ""
MsgBox "Label cleared.", vbInformation
End If
End Sub

Related

How do I avoid Userform Combobox runtime error?

Hopefully a simple question. I have some simple code for a combo box that runs during Combobox_Change().
Private Sub ComboBox1_Change()
If ComboBox1.Value = "" Then
Label3.Caption = ""
Else
Label3.Caption = Worksheets("Currency").Cells.Find(UserForm1.ComboBox1.Value).Offset(0, -1).Value
End If
End Sub
Private Sub UserForm_Initialize()
ComboBox1.List = [Currency!C2:C168].Value
Label3.Caption = ""
End Sub
But when you enter something that isn't part of the declared Combobox range it throws up a runtime error 'Object variable not set'. How do I fool proof this combobox and when any irregular entry is made that isn't part of the selection range for it to revert back to "" empty? Or pop up with an error box stating "Invalid Input"?
If Find fails to find anything it returns a null object. That returned object has no methods or properties so you can't take the offset() or value of it. To work around this you need to separate out the returned object and its methods/properties and test the validity of the returned object.
Private Sub ComboBox1_Change()
If ComboBox1.Value = "" Then
Label3.Caption = ""
Else
Dim fndrng As Range
'Get just the find range
Set fndrng = Worksheets("Currency").Cells.Find(UserForm1.ComboBox1.Value)
'Make sure find found something
If Not fndrng Is Nothing Then
'use the methods/properties we want
Label3.Caption = fndrng.Offset(0, -1).Value
Else
MsgBox "Selection not found", vbOKOnly, "Error"
End If
End If
End Sub
Private Sub UserForm_Initialize()
ComboBox1.List = [Currency!C2:C168].Value
Label3.Caption = ""
End Sub

VBA Multiple Textboxes Validation control

Dears,
I am preparing a simple userform to let a teacher to enter each student’s name and height in a class. There are two textboxes (textbox_name and textbox_height) and one “add to record” command button. I tried to make some validation control to prevent empty string to be entered. My validation control is in case textbox is empty, when the click the “add to record” button, the corresponding empty textbox turns pink; and when both textboxes are empty, both textboxes should turn pink, however only the first textbox turns pink in my below codes. Can you tell me why and how to correct it? Thanks.
Private Sub Cmd_addtorecord_Click()
If TextBox_Name = "" Then
TextBox_Name.BackColor = rgbPink
Exit Sub
End If
If TextBox_height = "" Then
TextBox_height.BackColor = rgbPink
Exit Sub
End If
'....
End sub
You can do it like this:
Private Sub Cmd_addtorecord_Click()
'ensure required fields have content
If FlagEmpty(Array(TextBox_Name, TextBox_height)) > 0 Then
MsgBox "One or more required values are missing", vbExclamation
Exit Sub
End If
'....
End Sub
'check required textboxes for content, and flag if empty
' return number of empty textboxes
Function FlagEmpty(arrControls) As Long
Dim i As Long, numEmpty As Long, clr As Long
For i = LBound(arrControls) To UBound(arrControls)
With arrControls(i)
clr = IIf(Len(Trim(.Value)) > 0, vbWhite, rgbPink)
.BackColor = clr
If clr = rngpink Then numEmpty = numEmpty + 1
End With
Loop
FlagEmpty = numEmpty
End Function
You're Exiting the sub before you get to the second textbox. Change your code to something like this:
Private Sub Cmd_addtorecord_Click()
If TextBox_Name = "" or TextBox_height = "" Then
If TextBox_Name = "" Then
TextBox_Name.BackColor = rgbPink
End If
If TextBox_height = "" Then
TextBox_height.BackColor = rgbPink
End If
Exit Sub
End If
'....
End sub

how to retrieve a value from an userform

I'm trying to write a code to trace every change made by the user on any worksheet. The user will input data and from time to time will erase said data and/or correct the original value they inserted. If the change is either deletion or modification, an Userform will pop up and the user will include a reason for that change. Right now I'm able to display the form everytime the user makes one of the changes mentioned before, but I'm not able to retrieve the reason, could you guys help me?
This is what I have for the UserForm
Private Sub CommandButton1_Click()
Dim msgvalue As VbMsgBoxResult
Dim value As String
msgvalue = MsgBox("Do you wish to save the change?", vbYesNo + vbInformation, "Confirm")
If msgvalue = vbNo Then GoTo Command
If msgvalue = vbYes Then
value = UserForm1.txtCmmt.Value
If value = "" Then GoTo Command
End
End If
Command:
MsgBox ("A reason must be provided")
With UserForm1
.txtCmmt.Value = ""
End With
End Sub
So if a user tries to delete a value, the code is the following:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim sLastAction As String
Dim Cell As Range
sLastAction = Application.CommandBars("Standard").Controls("&Undo").List(1)
For Each Cell In Target
If sLastAction = "Clear" Or sLastAction = "Delete" Or Left(sLastAction, 9) = "Typing ''" Then
UserForm1.Show 'this is where I'm stuck, I'm not sure how to retrieve the value from the form
End If
'the code continues to retrieve other info from the changes made, including the "reason"
Thanks for the help!
Try the next way, please:
Let us say that your text box where the comment will be written is named "txtComment".
Put this code in its Exit event:
Private Sub txtComment_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Me.txtComment.text <> "" Then
If ActiveSheet.Name <> "LogDetails" Then
Application.EnableEvents = False
Sheets("LogDetails").Range("A" & rows.count).End(xlUp).Offset(0, 5).Value = Me.txtComment.text
Application.EnableEvents = True
Unload Me
End If
End If
End Sub
Let the existing Worksheet_Change event as it is, only launching the form and maybe making a Public boolean variable (from a standard module) True (something boolStop) which will not allow changing anything in any worksheet until it is not False.
Then fill the text you need in the text box ("txtComment", or however you named it) and press Enter. If my above suggestion looks interesting for you, the last line of the text box event will be boolStop = False.
If you understand how to implement the above simple solution, you maybe will forget about a user form and use a simple InputBox, as in the next example:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address(0, 0) <> "E1" Then Exit Sub
Dim sLastAction As String, comValue As String
Dim Cell As Range
sLastAction = Application.CommandBars("Standard").Controls("&Undo").list(1)
For Each Cell In Target
If sLastAction = "Clear" Or sLastAction = "Delete" Or left(sLastAction, 9) = "Typing ''" Then
WritePlease:
comValue = InputBox("Please write the reason for cell """ & Cell.Address & """ (" & sLastAction & ").", "Reason, please")
If comValue = "" Then GoTo WritePlease
If ActiveSheet.Name <> "LogDetails" Then
Application.EnableEvents = False
'Stop
Sheets("LogDetails").Range("A" & rows.count).End(xlUp).Offset(0, 5).Value = comValue
Application.EnableEvents = True
End If
End If
Next
End Sub

Excel Userform to update existing Data

I would like to overwrite data using a Userform, I can call the data to the form based on a Combobox (unique reference from column A in my data sheet). I am failing to send updated data back, and am stuck on a Run-time error '13.
I have looked at a number of posts but cannot pick out a thread to success! Any help appreciated. I have left the code simple, to update the 4 column of that row. Ultimately I will expand from the 2nd column onwards.
Private Sub cmbtrade_Change() - this part works as expected
Dim trade_name As String
If Me.cmbtrade.Value = "" Then
MsgBox "Trade Can Not be Blank!!!", vbExclamation, "Trade"
Exit Sub
End If
trade_name = cmbtrade.Value
On Error Resume Next
Dim trade As Double
trade_name = cmbtrade.Value
TextBox16.Text = Application.WorksheetFunction.VLookup(trade_name,
Sheets("Sheet2").Range("A2:D43"), 4, False)
End Sub
The problem part....
Private Sub cmdupdate_Click()
If Me.cmbtrade.Value = "" Then
MsgBox "Trade Name Can Not be Blank", vbExclamation, "Trade"
Exit Sub
End If
trade_name = cmbtrade.Value
Sheets("sheet2").Select
Dim rowselect As Double
rowselect = Me.cmbtrade.Value (this is where my mismatch error occurs)
rowselect = rowselect + 1
Rows(rowselect).Select
Cells(rowselect, 4) = Me.TextBox16.Value
End Sub
enter image description here
Try this. You don't actually need to convert the combobox to a Long, but it's good practice I think.
Private Sub cmdupdate_Click()
If Me.cmbtrade.Value = "" Then
MsgBox "Trade Name Can Not be Blank", vbExclamation, "Trade"
Exit Sub
End If
Dim rowselect As Long
rowselect = CLng(Me.cmbtrade.Value) + 1
Sheets("sheet2").Cells(rowselect, 4) = Me.TextBox16.Value
End Sub

How to detect if user select cancel InputBox VBA Excel

I have an input box asking user to enter a date. How do I let the program know to stop if the user click cancel or close the input dialog instead of press okay.
Something like
if str=vbCancel then exit sub
Currently, user can hit OK or Cancel but the program still runs
str = InputBox(Prompt:="Enter Date MM/DD/YYY", _
Title:="Date Confirmation", Default:=Date)
If the user clicks Cancel, a zero-length string is returned. You can't differentiate this from entering an empty string. You can however make your own custom InputBox class...
EDIT to properly differentiate between empty string and cancel, according to this answer.
Your example
Private Sub test()
Dim result As String
result = InputBox("Enter Date MM/DD/YYY", "Date Confirmation", Now)
If StrPtr(result) = 0 Then
MsgBox ("User canceled!")
ElseIf result = vbNullString Then
MsgBox ("User didn't enter anything!")
Else
MsgBox ("User entered " & result)
End If
End Sub
Would tell the user they canceled when they delete the default string, or they click cancel.
See http://msdn.microsoft.com/en-us/library/6z0ak68w(v=vs.90).aspx
Following example uses InputBox method to validate user entry to unhide sheets:
Important thing here is to use wrap InputBox variable inside StrPtr so it could be compared to '0' when user chose to click 'x' icon on the InputBox.
Sub unhidesheet()
Dim ws As Worksheet
Dim pw As String
pw = InputBox("Enter Password to Unhide Sheets:", "Unhide Data Sheets")
If StrPtr(pw) = 0 Then
Exit Sub
ElseIf pw = NullString Then
Exit Sub
ElseIf pw = 123456 Then
For Each ws In ThisWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next
End If
End Sub
The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.
For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:
Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then 'I also tried with sRange.address and vbNullString
MsgBox ("Cancel pressed!")
Exit Sub
End If
MsgBox ("Your custom range is " & sRange.Address)
End Sub
The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:
Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
MsgBox ("Cancel pressed")
End Sub
So, the question is how to detect either an error or StrPtr()=0 with an If statement?
If your input box is an array, it does not work. I have solved it by adding a check for if it is an array first.
Dim MyArrayCheck As String
Dim MyPlateMapArray as variant
MyPlateMapArray = Application.InputBox("Select ....", Type:=8)
MyArrayCheck = IsArray(MyPlateMapArray)
If MyArrayCheck = "False" Then
Exit Sub
End If
I have solved it with a False like below
MyLLOQ = Application.InputBox("Type the LLOQ number...", Title:="LLOQ to be inserted in colored cells.", Type:=1)
If MyLLOQ = False Then Exit Sub
If user click cancel the sub will exit.
Another suggestion.
Create a message box when inputbox return null value. Example:
Dim PrC as string = MsgBox( _
"No data provided, do you want to cancel?", vbYesNo+vbQuestion, "Cancel?")
Sub TestInputBox()
Dim text As String
text = InputBox("Type some text")
If text = "" Then
MsgBox "button cancel pressed or nothing typed"
Else
MsgBox text
End If
End Sub
Inputbox send a boolean False value when Cancel is pressed.
contenidoy = Application.InputBox("Cantidad = ", titulox, contenidox, , , , , Type:=1)
'ESC or CANCEL
If contenidoy = False Then
MsgBox "Cancelado"
Else
MsgBox "Edición aceptada"
'End If

Resources