My VBA program processes some operations on an input typed by the user and eventually gives back a result.
At some point, I want to have some userform showing up and "adjusting" the research. For example, if the user typed a state and a city which doesn't fit, it would show "Did you mean city in state ? ". Then, clicking on yes would take into account the modification, clicking no wouldn't change anything.
I have tried this, as found in some tutorials :
city = sMain.Range("J12").Value
province = sMain.Range("J6").Value
provinceSugg = sCurrent.Cells(p, db_column).Value
If province = "" And city <> "" Then
UserForm2.Show
UserForm2.Label1 = "Do you mean : " & city & " in " & provinceSugg
Else
End If
Unfortunately, it doesn't work at all, whatever text I write for Label1 and whatever way of writing I use (Label1.Caption = , Userform2.Label1.Caption = , Label1 = , etc.), still no change.
Thanks for helping me to fix this !
Set the caption before showing the form...like this:
city = sMain.Range("J12").Value
province = sMain.Range("J6").Value
provinceSugg = sCurrent.Cells(p, db_column).Value
If province = "" And city <> "" Then
UserForm2.Label1 = "Do you mean : " & city & " in " & provinceSugg
UserForm2.Show
Else
End If
Use vbModeless ..
If province = "" And city <> "" Then
UserForm2.Show vbModeless
UserForm2.Label1 = "Do you mean : " & city & " in " & provinceSugg
Else
End If
Related
I have a userform where you have to enter data into textboxes and then press a button to put the data into the sheet. When I'm typing into the last textbox and I'm done, I click the button and it doesn't respond. Also, I have noticed that my cursor keeps blinking inside the last textbox so I guess there's a problem there (while focused not able to click a button)?
In total I have 4 textboxes, 3 of them use data validation after their value has been updated. The last one does not have data validation.
The weird thing is that, next to the "next button", I have a button to clear the fields and that one works just fine. Below an image from my userform with a little bit of explanation because it's in another language (Dutch). Can anyone help me? Thanks!
The code used for the "next" button is:
Note: the data gets validated not only when they updated the value of the textbox, but also an extra time when they click the next button.
Private Sub AddNextBtn_Click()
AddValueMod.AddDisplayOverview
End Sub
Sub AddDisplayOverview() 'This sub is in the "AddValueMod" module
'Check if information is valid via a function
If AddInformationValid("AccountSelector", True) And AddInformationValid("Date", True) And AddInformationValid("Amount", True) And AddInformationValid("Description", True) Then
'If valid, retrieve entered values
Dim account, dDate, amount, description As String
account = main.AddAccountSelector.Value
dDate = main.AddDateInput.Value
amount = main.AddValue.Value
description = main.AddDescription.Value
'Ask for sheet-writing-confirmation
overview = MsgBox("Kloppen volgende gegevens (kijk goed na!)?" & vbCrLf & vbCrLf & "Rekening: " & account & vbCrLf & "Datum: " & dDate & vbCrLf & "Bedrag: " & amount & vbCrLf & "Beschrijving: " & description & vbCrLf & "Vermeerdering/vermindering: Waarde wordt vermeerderd", vbYesNo + vbQuestion, "Kloppen volgende gegevens?")
If overview = vbYes Then
'Write data to sheet
AddValueMod.AddEnterDataIntoSheet
End If
End If
End Sub
And for the "clear fields" button:
Private Sub AddClearFieldsBtn_Click()
AddValueMod.AddClearFields (True)
End Sub
Sub AddClearFields(askForConfirmation As Boolean) 'This sub is in the "AddValueMod" module
grey = RGB(128, 128, 128)
'If askForConfirmation = True, ask for confirmation before clearing fields
If askForConfirmation = True Then
confirmationMessage = MsgBox("Bent u zeker dat u de velden wilt leegmaken?" + vbCrLf + "U zal terug opnieuw moeten beginnen.", vbYesNo + vbQuestion, "Velden leegmaken?")
If confirmationMessage = vbYes Then
'Clear fields
main.AddAccountSelector.Value = ""
main.AddDateInput.Value = ""
main.AddValue.Value = ""
main.AddDescription.Value = ""
End If
ElseIf askForConfirmation = False Then
'Clear fields
main.AddAccountSelector.Value = ""
main.AddDateInput.Value = ""
main.AddValue.Value = ""
main.AddDescription.Value = ""
End If
'Reset the textboxes' borders (they change if an input error occurred)
main.AddAccountSelectorError.Visible = False
main.AddAccountSelector.BorderStyle = fmBorderStyleSingle
main.AddAccountSelector.BorderColor = grey
main.AddDateInputError.Visible = False
main.AddDateInput.BorderStyle = fmBorderStyleSingle
main.AddDateInput.BorderColor = grey
main.AddValueError.Visible = False
main.AddValue.BorderStyle = fmBorderStyleSingle
main.AddValue.BorderColor = grey
main.AddDescriptionError.Visible = False
main.AddDescription.BorderStyle = fmBorderStyleSingle
main.AddDescription.BorderColor = grey
End Sub
P.S.: I've already tried a possible solution with IsCancel = True/False that I found online in this article. It's possible it didn't work because the article is not quite related to my problem but I felt like I should mention it :).
You did not provide all relevant code. AddInformationValid() and AddEnterDataIntoSheet are missing.
However, if the AddInformationValid() returns False on any item, the behaviour is just as you describe. In AddDisplayOverview() there will be no error message, the AddEnterDataIntoSheet sub will be bypassed and on return from the button handler the cursor remains flashing in the last entry field.
You need to verify and correct the AddInformationValid() Function.
I also strongly recommend to show an error message if the data validation fails.
I have been figuring out how to pop up msg box if there is error. I have below code but this code does not jump to error handler if there is error and Exit the sub.
Sub Validate_Region()
Dim str_DEPARTMENT_NAME As String
On Error GoTo Reion_Error
If Left(Range("M4"), 2) = "As" Then
str_DEPARTMENT_NAME = "India"
ElseIf Left(Range("M4"), 2) = "ME" Then
str_DEPARTMENT_NAME = "Middle East"
End If
'Get value of region selected in Master File
str_regionvalue = Workbooks("Master Report").Sheets("Home").Range("T8")
If str_regionvalue = str_DEPARTMENT_NAME Then
MsgBox ("You have selected " & str_regionvalue & " region"), vbInformation
End If
Exit Sub
Reion_Error:
MsgBox ("Please select the correct Region.") & vbNewLine & vbNewLine & ("You have selected " & str_regionvalue & " region" & " In Home Sheet of Master Report and pulled the data for " & str_DEPARTMENT_NAME & " region"), vbCritical
ActiveWorkbook.Close
End Sub
I just copy/pasted your code and it works well for me:
I don't know from where this sub is called and what type of variable is used on str_regionvalue (seems like Variant)
So what can you do with this:
Get rid of Exit Sub on line #19.
Put Err.Number check in your error handler:
Reion_Error:
If Err.Number <> 0 Then
MsgBox ("Please select the correct Region.") & vbNewLine & vbNewLine & ("You have selected " & str_regionvalue & " region" & " In Home Sheet of Master Report and pulled the data for " & str_DEPARTMENT_NAME & " region"), vbCritical
'by the way, you can try to set ActiveWorkbook.Saved to True, to get rid from pop-ups on Close
ActiveWorkbook.Close
End If
Try to look for error number thru debugging (debug.print err.number or place some stop's to do this manually). Or add err.number to Watches and check Break when value changes so you can track where error raised and cleared (if raised).
Err object
P.S. You got some ridiculous MsgBoxes, if you really like parentheses, use them like this:
Call MsgBox("Please select the correct Region." & vbNewLine & vbNewLine & _
"You have selected " & str_regionvalue & " region" & " In Home Sheet of Master Report and pulled the data for " & str_DEPARTMENT_NAME & " region", vbCritical)
Under Tools >> Options in the VB Editor: on the General tab make sure you don't have "Error trapping" set to "Break on all errors"
Check your syntax, you have quite a few unnecessary brackets and commas in your msgbox statements. Try something like:
returnval = MsgBox ("Put message here" , vbInformation)
OR
MsgBox "another message " & vbnewline & "some more message", vbcritical
The code looks fine and compiles now but I think your error may be elsewhere. Possibly in:
str_regionvalue = Workbooks("Master report").Sheets("Home").Range("T8")
I'd suggest:
Leave the 'exit sub' in. It's correct.
Add 'Option Explicit' to the top of the code - it will force you to declare all variables (str_regionvalue isn't declared)
Set your Under Tools >> Options in the VB Editor: to 'Break on Unhandled Errors'.
Put in a breakpoint (Debug >> Add Watch) at the top of the code and run through it step by step using Debug >> Step Into.
I have used the spreadsheet provided here to create a ribbon and it worked great as long as it was all about assigning macros to the buttons. However, I wanted to include configuration details in a group of the tab to make it visible all the time without consuming excel sheet real estate. Here is the to-be state:
Group in the custom tab
I have a small macro to select environment and identify the values of various fields shown in the image. Here is what the code looks like:
Sub Change_Configuration()
Dim ConfigButton As Object
Dim Labeling As String
'SelectEnvironment.Show
Environment = "PROD"
If Environment = "QAS" Then
SourceSystem = "ABC"
TargetSystem = "DEF"
SourceSchema = "EFG"
TargetSchema = "GHI"
ElseIf Environment = "PROD" Then
SourceSystem = "IJK"
TargetSystem = "JKL"
SourceSchema = "LMN"
TargetSchema = "NOP"
End If
GetLabel ConfigButton, Labeling 'I do not know what to do here
End Sub
I know that Get Label is the way to do it but I just do not have any clue as to how to achieve what I want to achieve. My current GetLabel callback works fine when I open the excel file and populates default values correctly (The IF part). I tried to include "Else" part to update label but it just does not work.
Original Code:
Sub GetLabel(ByVal control As IRibbonControl, ByRef Labeling)
Select Case control.ID
Case "CustomTab": Labeling = "TEST_RIBBON"
Case "GroupE": Labeling = "Configuration Details"
Case "eButton01": Labeling = "Change Environment"
Case "eButton02": Labeling = "Selected Environment" & " - " & "QAS"
Case "eButton03": Labeling = "Source System" & " - " & "ABC"
Case "eButton04": Labeling = "Source Schema" & " - " & "DEF"
Case "eButton05": Labeling = "Target System" & " - " & "GHI"
Case "eButton06": Labeling = "Target Schema" & " - " & "IJK"
End Select
End Sub
When I open the excel, all labels have values as defined above.
Below is the Modified code (unsuccessful effort to modify to change the label based on Change_Configuration Macro). Please note that modified code also does not throw any error when my workbook is opened and displays values correctly.
Sub GetLabel(ByVal control As IRibbonControl, ByRef Labeling)
If Environment = vbNullString Then
Select Case control.ID
Case "CustomTab": Labeling = "My Tab"
Case "GroupE": Labeling = "Configuration Details"
Case "eButton01": Labeling = "Change Environment"
Case "eButton02": Labeling = "Selected Environment" & " - " & "QAS"
Case "eButton03": Labeling = "Source System" & " - " & "ABC"
Case "eButton04": Labeling = "Source Schema" & " - " & "DEF"
Case "eButton05": Labeling = "Target System" & " - " & "EFG"
Case "eButton06": Labeling = "Target Schema" & " - " & "GHI"
End Select
Else
Select Case ConfigButton
Case "eButton02": Labeling = "Selected Environment" & " - " & Environment
Case "eButton03": Labeling = "Source System" & " - " & SourceSystem
Case "eButton04": Labeling = "Source Schema" & " - " & SourceSchema
Case "eButton05": Labeling = "Target System" & " - " & TargetSystem
Case "eButton06": Labeling = "Target Schema" & " - " & TargetSchema
End Select
End If
End Sub
Your help is greatly appreciated.
-Jevich
Solved it - Had to include onload call back for Ribbon after adjusting XML and then Invalidate function.
too little relevant code to be sure to help you through
but try just changing:
Select Case ConfigButton
to:
Select Case control.ID
and watch what happens...
I am creating a code that opens and imports data from a file that is selected based on a client's name. Each time a client is opened, a file is saved for them with their name and date of birth (without slashes).
A sample file would look like C:\Data\Clients\John Doe 01011900.xlsx. An InputBox on button-click provides a client's name, but what I'm getting stuck on is if there are 2 or more John Does in the folder.
Check = Application.InputBox(prompt:="What is your client's first and last name?", Type:=2)
FilePath = "C:\Data\Clients\" & Check & "*.xlsx"
If Dir(FilePath, vbDirectory) = "" Then
Exit Sub
End If
DOB = MsgBox("Is this your client's date of birth? " & " " & Chr(149) & " " & Mid(Dir(FilePath), Len(Dir(FilePath)) - 12, 2) & "/" & Mid(Dir(FilePath), Len(Dir(FilePath) - 10, 2) & "/" & Mid(Dir(FilePath), Len(Dir(FilePath) - 8, 4) & " " & Chr(149), vbYesNoCancel)
If DOB = vbYes Then
Workbooks.Open (FilePath)
'Transfer Data
ActiveWorkbook.Close False
ElseIf DOB = vbNo Then
'Try again.
ElseIf DOB = vbCancel Then
'Do nothing.
End If
My confusion is occurring at the DOB = vbNo, when someone says the date of birth does not match (meaning the next client with the same name needs to be selected). Everything else works great so far, so I just need help with the re-selection of the next file with the same name.
You can loop through all the matches by adding a strDir = Dir at the end of your loop, which will exit after the match is met and not accepted (as the length of StrDir will be 0)
update
I realise the code looks a little strange but this is the way Dir works, ie each time it is called it looks for the same match as the initial Dir until it reaches the end of the list. See Loop through files in a folder using VBA?
ie
Do While Len(strDir) > 0
DOB = MsgBox("Is this your client's date of birth?", vbYesNoCancel)
If DOB = vbCancel Then Exit Do
If DOB = vbYes Then
Workbooks.Open (filepath)
ActiveWorkbook.Close False
Exit Do
End If
strDir = Dir
Loop
This is what I would do:
First, use string comparison to find all the files in the directory that starts with John Doe and store them in a dynamic array.
Use For...Each statement to go through the files, and use
Dir(FilePath) LIKE "John Doe*" to find your candidates.
Then use a Do...While loop to go through the files in the array until you find your match.
I could write the entire code for you but then you'd miss all the fun...
It's me again. ^_^
Can I ask how can I filter a specific record by category? I only know how to filter only one category. Here's my code. Please help me. Thanks!
If txtName.Text = "" Then
MsgBox "Please enter what you want to filter.", vbInformation, "Message Box"
txtName.SetFocus
Else
If Not myRS.EditMode And myRS.BOF = True Then
MsgBox "No record found!", vbCritical, "Search Result"
Else
myRS.Filter = "TL LIKE '" & txtName.Text & "*'"
Set DataGrid1.DataSource = myRS
DataGrid1.Columns(0).Caption = "Work Group"
DataGrid1.Columns(1).Caption = "Team Leader"
DataGrid1.Columns(2).Caption = "Dept Head"
DataGrid1.Columns(3).Caption = "Participants"
DataGrid1.Columns(4).Caption = "Date Created"
DataGrid1.Columns(5).Caption = "Coach"
DataGrid1.Columns(6).Caption = "Problem"
DataGrid1.Columns(7).Caption = "Measure Impacted"
DataGrid1.Columns(8).Caption = "Status"
DataGrid1.Columns(9).Caption = "Where"
DataGrid1.Columns(10).Caption = "When"
DataGrid1.Columns(11).Caption = "How Much/Many"
DataGrid1.Columns(12).Caption = "Who"
Assuming your query to populate myRS looks something like
Select WorkGroup, TL, DeptHead, ...., Category From blah blah
You could change your line to
myRS.Filter = "TL LIKE '" & txtName.Text & "*' OR Category LIKE '" & txtName.Text & "*'"
which would give you both TL and categories that match the txtName, or you could create a new text box in addition to txtName, perhaps txtCategory, and then change the line to
myRS.Filter = "TL LIKE '" & txtName.Text & "*' AND Category LIKE '" & txtCategory.Text & "*'"
add a combo box in the form. and fill it
dim item
Combo1.clear
For Each item In Array("Work Group", "Team Leader", "Dept Head" _
, "Participants", "Date Created", "Coach" _
, "Problem", "Measure Impacted", "Status" _
, "Where", "When", "How Much/Many", "Who")
Combo1.AddItem item
Next
then :
i=combo1.listindex
if(i=-1) then
'ErrorMessageHere
exit sub
end if
myRS.Filter = "[" & myRS.Fields(i).Name & "] LIKE '*" & txtName.Text & "*'"