I do not want my Userform to retain its values - vba

I have created a userform that has a textbox which requires an input of numbers, however when I add invalid characters I have coded the form to give an error message and to reset the form. The problem is after error message when people put the right characters in the boxes, the userform has retained the old characters (that do not work) and is trying to caclulate with those. Im not sure if my question is understandable or not. I appreciate any help
ErrorCheckAmount:
If Amount = "" Then
MsgBox "Your Have Entered Invalid Characters, Please Try Again", vbOKOnly, "Error"
Unload UserForm1
UserForm1.Show
ElseIf IsNumeric(Amount) Then
GoTo ErrorCheckQuantity
Else
MsgBox "Your Have Entered Invalid Characters, Please Try Again", vbOKOnly, "Error"
Unload UserForm1
UserForm1.Show
End If
ErrorCheckQuantity:
If Quantity = "" Then
MsgBox "Your Have Entered Invalid Characters, Please Try Again", vbOKOnly, "Error"
Unload UserForm1
UserForm1.Show
ElseIf IsNumeric(Quantity) Then
GoTo Start
Else
MsgBox "Your Have Entered Invalid Characters, Please Try Again", vbOKOnly, "Error"
Unload UserForm1
UserForm1.Show
End If

You seem to be saying that you want to DELETE the user's input and make them start over. I think it would be better to leave their input and let them remove the invalid characters (maybe tell them what you're considering invalid ... should they only include numbers? or just don't use special characters?). So - that solves your immediate problem by just deleting the unload / show commands!
If you really want to delete the user's input - I'd recommend only deleting the text boxes where they entered invalid data ... so - for Quantity - you could just set the [textboxname].value = "" instead of form unload and show.
If you want to be 100% certain that the form will be empty when your user opens it - you could add code to the Initialize procedure to clear the values.
Private Sub UserForm_Initialize()
txtAmount.Value = ""
txtQuantity.Value = 0
end sub
Tim Williams makes a great comment - that the code you posted doesn't provide enough context for a full answer. But - I think one of the three approaches above should work for you.

Related

VBA Mismatch Error for outputting textbox entry with calculation to Excel sheet?

quite new to VBA and have what must be a rather simple question, but data types keep on giving me problems. I'm developing a MultiPage UserForm in VBA, and would like to output user input to Excel, to run calcs in the sheet and then provide an answer on a subsequent page in the UserForm. I've tried looking online for solutions, but nothing is clicking. Basically trying this:
Sheets("Calcs").Range("DataStart").Offset(0, 11).Value = CRBinQnt / 100 * Sheets("Calcs").Range("DataStart").Offset(0, 6).Value
So a user would input a number into a text box CRBinQnt, and I want to assign that number to Sheets("Calcs").Range("DataStart").Offset(0, 11).Value in Excel Worksheet. Before inputting that value, I would like it to be divided 100 (to be a percentage) and multiplied by a fixed value already in the worksheet Sheets("Calcs").Range("DataStart").Offset(0, 6).Value.
I've tried Dim CRBinQnt as long, short etc and CDbl(CRBinQnt) to no avail. Not sure why I keep getting mismatch error. Any help would be most appreciated. New to this, so if any further clarifications are required please let me know.
What I would do is using the following code for validating your TextBox CRBinQnt. The event CRBinQnt_Exit runs when the TextBox looses focus, so we validate its content.
Private Sub CRBinQnt_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Me.CRBinQnt.Value = vbNullString Then Exit Sub ' this allows the TextBox to be left empty (if you don't want that remove it). If you don't allow it the user will be trapped in the TextBox until he enters a valid number. He even cannot abort.
If Not IsNumeric(Me.CRBinQnt.Value) Then
' if the value is not numeric error and do not allow to leave the TextBox
MsgBox "CRBinQnt needs to be an integer number!", vbExclamation
Cancel = True
ElseIf CStr(CLng(CRBinQnt.Value)) <> CRBinQnt.Value Then
' if the value is numeric check if it is an integer number, if not do not allow to leave the TextBox
MsgBox "CRBinQnt needs to be an integer number!", vbExclamation
Cancel = True
End If
End Sub
Then you should be able to use this without getting an error.
If Not CRBinQnt.Value = vbNullString Then
Sheets("Calcs").Range("DataStart").Offset(0, 11).Value = CLng(CRBinQnt.Value) / 100 * Sheets("Calcs").Range("DataStart").Offset(0, 6).Value
Else
' user did not input anything so abort …
End If

Check if field is null or blank before closing form on Access using VBA

I've been playing around this with VBA code to check if the field is empty before closing the form. If the field is empty, I want it to display a Yes/No message box.
The issue that I'm having is that when I click No after the message appears (if the field is blank), it continues to close the form. Instead, when I click No, I want the focus to set on the field that needs to be addressed.
Here's my code:
Private Sub Close_Click()
If IsNull(cboTxtBx) Then
MsgBox("Do you want to continue?", vbYesNo, "X is Blank!")
If vbYes Then
DoCmd.Close
Else
cboTxtBx.SetFocus
End If
Else
DoCmd.Close
End If
End Sub
I've also replaced IsNull() with Len(cboTxtBx.value & "") = 0 and still have the same issue.
I've also removed the last DoCmd.Close statement but the form still closes once I hit No.
I'm sure the solution lies within the sequence of my code but I'm not proficient with VBA and I'm struggling to get this code to work.
One small note, cboTxtBx is a combo box. Not sure if that interrupts the code in any way.
After you answer the message box its result is interpreted nowhere, so the code goes on.
You would have to use it like this to really check the result of the message box:
If MsgBox("Do you want to continue?", vbYesNo, "X is Blank!") = vbYes Then
DoCmd.Close
Else
cboTxtBx.SetFocus
End If

Closing msgbox from another file

I'm using several excel files and each one is making some calculations using VBA. Now I'm working on one file which will run each file one after another and calculate them all with one click. Unfortunately at the end of calculation for each file there is Msgbox "Report updated" and my macro stops and is waiting to confirm "OK" manually before it will close first file and open next one.
I cannot remove this lines with msgboxes because some people will use just one file and they need to be informed that everything is finished.
And here is my question: How can I close this msgbox automatically?
Thanks in advance
I think it is impossible, because MsgBox is modal. But why your macro displays it at first? You may add conditional instruction that checks if the sheet on which it works is displayed. Something like:
If ActiveSheet.Name = wsProcessedSheet.Name Then MsgBox "Report updated"
So, the message will be displayed for normal user and not for your supermacro. Alternatively, you could disable the MsgBox only for your machine:
If Environ("username")<> "your user name" Then MsgBox "Report updated"
Thank you for interesting ideas.
I've just figured out different solution. Originally I had button which run macro Update()
Sub Update()
...calculations....
Msgbox "Report updated"
End Sub
Now I removed msgbox from this macro and created two macroslike below:
Sub ButtonClick()
Call Update
Msgbox "Report updated"
End Sub
Sub Update()
...calculations....
End Sub
And now button is running macro ButtonClick and in external file I can use macro Update() which didn't contain msgbox.
But I still wondering if there is any way to confirm msgbox alerts

How to make macro create an alert when changing a value in the drop down list

I am currently working on an project that contains forms. Therefore users pick a specific type of form from the drop down list. How do you create an alert in excel using macro when a user picks certain type of form from the dropdown list. And after completing the form and before changing it I want to issue an alert saying that please make sure to Save the form. How is this done in excel.
Thank you for your help.
You can using event "Change" in Combobox
Private Sub ComboBox1_Change()
MsgBox "Value changed"
End Sub
Or check value after change, like this
Private Sub ComboBox1_Change()
If ComboBox1.Value = "ABC" Then
MsgBox "Value changed"
End If
End Sub
And about "alert Save the form", because I don't know your form, so I can't give you ideal.

Excel VBA - Run Time Error 13 Type Mismatch

I'm creating a task list style excel sheet in which people are assigned tasks and can use the sheet as a progress tracker.
Once a task is completed, a person marks it off as completed and the sheet pops up with a message box asking whether a change reference number is needed.
However, when I filter by say, the person who completed the task, and try to add a new row for a new task I get the Run Time Error 13 Type Mismatch. I think it's because my VBA is constantly checking for the status of the task to be completed, so when you create a blank row, there's nothing in the status column.
Here's the below code that's highlighted with the error message.
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim answer
If Not Intersect(Target, Range("H5:H1000")) Is Nothing Then
If (Target.Value) = "Completed" Then
answer = MsgBox("Do you need to add a change reference?", vbYesNo + vbQuestion, "Change Reference Reminder")
If answer = vbYes Then
MsgBox "Add in the column to the right", , ("Change Reference Tip")
Else
'do nothing'
End If
End If
End If
End Sub
There are a few things going on here; too many to describe in a comment.
First of all, the Worksheet_Change sheet macro is triggered by an event, specifically when one or more cells' contents change. If you want to avoid heavy processing when you insert a row (subsequently changing the values of many cells), you need it to kick out if Target is more than a single cell. Typically, including If Target.cells.count > 1 then exit sub as the first line is sufficient to accomplish this. This is especially important as you want to compare a single changed cell's value to Completed.
Your code as supplied doesn't actually change anything but it looks like at some point it will be intended to. In order that changing a cell's value does not launch a second iteration of the same Worksheet_Change event maco (subsequently trying to run on top of itself) you would halt event handling temporarily and restart it just before leaving the macro.
If you turn off events, you need error handling so that they are turned back on in case of an error. Errors can occur to the best written code procedure and you want to catch and report the error to somewhere like the Immediate window then turn the event handling back on before safely exiting the event macro.
Minor point but I never Dim a variable until my boolean conditions dictate that I am actually going to use it.
With these 3½ things in mind, the sample code provided might be better as,
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Range("H5:H1000")) Is Nothing Then
On Error GoTo Erreur
Application.EnableEvents = False
If LCase(Target.Value) = "completed" Then
Dim answer As Variant
answer = MsgBox("Do you need to add a change reference?", vbYesNo + vbQuestion, "Change Reference Reminder")
If answer = vbYes Then
MsgBox "Change references are added in the column to the right." _
& Chr(10) & Chr(10) & "Let's go there now.", vbOKOnly, "Change Re ference Tip"
Target.Offset(0, 1).Activate
Else
'do nothing'
End If
End If
End If
GoTo Fìn
Erreur:
Debug.Print Err
Fìn:
Application.EnableEvents = True
End Sub
I've added one line of code that moved the user to the cell one column to the right of the cell that triggered the event.