How can i write the code "If i click "cancel" in the dialog box,the dialog box will close and the field will show nothing."? - dialog

Sorry, my statement is too long...
I have a form,the form have a button and field:Button name and field name are track reason.
if i click the button , will show an options box(options box name is askme).Among the options,have an option,the name called "other" , and it's for user to write other track reason.
If i choose the "other",then will show a dialog box to write other track reason.If i write something in dialog box(example:test),the field will show test,and the dialog box will close.If i click "cancel" in the dialog box,the dialog box will close and the field will show nothing.
Following is the code for button:
data(0) = "New vendor"
data(1) = "More than tracked amount"
data(2) = "Change vendor"
data(3) = "other"
askme = ws.prompt(PROMPT_OKCANCELLIST,"Track reason","Please choose the reason..." , data(0) , data())
If askme = "" Then
Call uipr.FieldSetText("TRACK_MARK" ,"")
uipr.Refresh
Exit Sub
Else
If askme = data(0) Or askme = data(1) Or askme = data(2) Then
Call uipr.FieldSetText("TRACK_REASON" , askme + username(0) + " " + Cstr(temp_servertime) + ")" )
Else
Call ws.DialogBox("TrackComments" , True , True , False , False , False , False , "Please enter other reason..." , , True , False)
Call uipr.FieldSetText("TRACK_REASON" , "(" + uipr.FieldGetText("ANOTHER_REASON") + username(0) + " " + Cstr(temp_servertime) + ")" )
End If
End If
And now,my question is...How can i write the code "If i click "cancel" in the dialog box,the dialog box will close and the field will show nothing."?
Because the problem is at here:
Call ws.DialogBox("TrackComments" , True , True , False , False , False , False , "Please enter other reason..." , , True , False)
Call uipr.FieldSetText("TRACK_REASON" , "(" + uipr.FieldGetText("ANOTHER_REASON") + username(0) + " " + Cstr(temp_servertime) + ")" )
Now,I click the "cancel",the dialog box will close,but the field will show(example: ( Ariel 2020/02/25 02:20:00PM)).
How should i do??????

You need to CHECK if the user pressed OK or cancel. At the moment you don't do this.
Change your code like that:
Dim ok as Variant
ok = ws.DialogBox("TrackComments" , True , True , False , False , False , False , "Please enter other reason..." , , True , False)
If ok then
Call uipr.FieldSetText("TRACK_REASON" , "(" + uipr.FieldGetText("ANOTHER_REASON") + username(0) + " " + Cstr(temp_servertime) + ")" )
Else
Call uipr.FieldSetText("TRACK_REASON" , "" )
End If
In addition I would suggest to use the backend class NotesDocument to set the text, then you can make the "TRACK_REASON"- field computed (Formula: #ThisValue) and the user cannot edit it directly. This is not possible when using frontendclass NotesUIDocument.
Then your code would be:
If ok then
Call uipr.Document.ReplaceItemValue("TRACK_REASON" , "(" + uipr.Document.GetItemValue("ANOTHER_REASON")(0) + username(0) + " " + Cstr(temp_servertime) + ")" )
Else
Call uipr.Document.ReplaceItemValue("TRACK_REASON" , "" )
End If

Related

Userform button not working when typing in a textbox vba

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.

check value in the array in Vbscript

I have one array app.getValue("Model.OutputArrays.FinalCompleteFileName_Array")="6F_HMBDConfig_978153ewnqsettgb73171_1219_31_640.pdf","6F_HMBDConfig_978153ewnqsettgb73171_1219_31_640.pdf","6F_HMBDConfig_978153ewnqsettgb73171_1219_31_640.pdf"
I have to apply a condition or check in the array if pdfname is already exist in the array then it will go to under If condition. But for the below code pdfname is always going to the Else condition even the pdfname is present in the filename_array.
please correct me where i am going wrong.
sub run
pdfname = "6F_HMBDConfig_978153ewnqsettgb73171_1219_31_640.pdf"
filename_array = app.getValue("Model.OutputArrays.FinalCompleteFileName_Array")
TestArray = Split(filename_array , ",")
For i=Lbound(TestArray) to Ubound(TestArray)
If StrComp(TestArray(i), pdfname , 1) = 0 Then
CompareStrings = True
MsgBox("Found " & pdfname & " at index " & i)
Else
CompareStrings = False
MsgBox "String not found!"
End If
Next
end sub
It seems that the app.getvalue is returning a string containing the pdf file names with each name surrounded by double-quotes. So, remove those double-quotes as shown below and run the code again.
Replace this:
filename_array = app.getValue("Model.OutputArrays.FinalCompleteFileName_Array")
With:
filename_array = replace(trim(app.getValue("Model.OutputArrays.FinalCompleteFileName_Array")),"""","")
Alternative Solution:
If you don't want to use the replace method, you can modify your if condition to use the instr method instead of strcomp method as shown below:
If InStr(1,TestArray(i), pdfname , 1) > 0 Then
CompareStrings = True
MsgBox("Found " & pdfname & " at index " & i)
Else
CompareStrings = False
MsgBox "String not found!"
End If

How to assign password to secure string in VB Script

I have a script comprising of batch files that generate powershell scripts. I've taken it upon myself to accomplish the same task via VB Script. So far I've assigned most of the info I need to strings. But I would like to have a prompt for a password that is stored as a secure string and can be outputted to a text file for later use in further scripts. So far the only code I've found doesn't work I think perhaps because it was intended for VB rather than VBS. Any help greatly appreciated.
The powershell code previously used was.
echo Please enter admin credentials (This will be stored in a secure string:
powershell -Command "& { read-host -assecurestring | convertfrom- securestring | out-file C:\S3BS\reports\input.txt; } "
You can use this small code with powershell and batch
#ECHO OFF
Title Type a password with powershell and batch
:CheckPassword
Mode con cols=50 lines=3
cls & color 0A & echo.
set MyPassword=Hackoo
set "psCommand=powershell -Command "$pword = read-host 'Enter your password' -AsSecureString ; ^
$BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set password=%%p
if %MyPassword%==%password% (Goto:Good) else (Goto:Bad)
exit/b
::***********************************************************************************************
:Good
Cls & Color 0A
echo(
echo Good Password
TimeOut /T 2 /NoBreak>nul
Exit
::***********************************************************************************************
:Bad
Cls & Color 0C
echo(
echo Bad password
TimeOut /T 1 /NoBreak>nul
Goto:CheckPassword
::***********************************************************************************************
I think this function PasswordBox can help you, just give a try ;)
' Just an example of how to use the function
'
wsh.echo "You entered: ", _
Join(PasswordBox("Enter UID and password", _
"Testing"), ", ")
' A function to present a Password dialog in a VBS (WSF)
' script
' Requires WScript version 5.1+
' Tom Lavedas <tlavedas#hotmail.com>
' with help from and thanks to Joe Ernest and
' Michael Harris
'
' modified 1/2008 to handle IE7
'
Function PasswordBox(sPrompt,sDefault)
set oIE = CreateObject("InternetExplorer.Application")
With oIE
' Configure the IE window
.RegisterAsDropTarget = False
.statusbar = false : .toolbar = false
.menubar = false : .addressbar = false
.Resizable = False
.Navigate "about:blank"
Do Until .ReadyState = 4 : WScript.Sleep 50 : Loop
' Test for IE 7 - cannot remove 'chrome' in that version
sVersion = .document.parentWindow.navigator.appVersion
if instr(sVersion, "MSIE 7.0") = 0 Then .FullScreen = True
.width = 400 : .height = 270
' Create the password box document
With .document
oIE.left = .parentWindow.screen.width \ 2 - 200
oIE.top = .parentWindow.screen.height\ 2 - 100
.open
.write "<html><head><" & "script>bboxwait=true;</" _
& "script><title>Password _</title></head>"_
& "<body bgColor=silver scroll=no " _
& "language=vbs style='border-" _
& "style:outset;border-Width:3px'" _
& " onHelp='window.event.returnvalue=false" _
& ":window.event.cancelbubble=true'" _
& " oncontextmenu=" _
& "'window.event.returnvalue=false" _
& ":window.event.cancelbubble=true'" _
& " onkeydown='if ((window.event.keycode>111)"_
& " and (window.event.keycode<117)) or" _
& " window.event.ctrlkey then" _
& " window.event.keycode=0" _
& ":window.event.cancelbubble=true" _
& ":window.event.returnvalue=false'" _
& " onkeypress='if window.event.keycode=13" _
& " then bboxwait=false'><center>" _
& "<div style='padding:10px;background-color:lightblue'>" _
& "<b>&nbsp" & sPrompt & "<b>&nbsp</div><p>" _
& "<table bgcolor=cornsilk cellspacing=10><tr><td>" _
& " <b>User:</b></td><td>" _
& "<input type=text size=10 id=user value='" _
& sDefault & "'>" _
& "</td><tr><td> <b>Password:</b></td><td>" _
& "<input type=password size=12 id=pass>" _
& "</td></tr></table><br>" _
& "<button onclick='bboxwait=false;'>" _
& " Okay " _
& "</button> <button onclick=" _
& "'document.all.user.value=""CANCELLED"";" _
& "document.all.pass.value="""";" _
& "bboxwait=false;'>Cancel" _
& "</button></center></body></html>"
.close
Do Until .ReadyState = "complete" : WScript.Sleep 100 : Loop
.all.user.focus
.all.user.select ' Optional
oIE.Visible = True
CreateObject("Wscript.Shell")_
.Appactivate "Password _"
PasswordBox = Array("CANCELLED")
On Error Resume Next
Do While .parentWindow.bBoxWait
if Err Then Exit Function
WScript.Sleep 100
Loop
oIE.Visible = False
PasswordBox = Array(.all.user.value, _
.all.pass.value)
End With ' document
End With ' IE
End Function
If you are executing the VBScript via cscript.exe something like;
cscript.exe /nologo "test.vbs"
You can use the WScript object to access the StdIn (for input) and StdOut (for output) streams to the command window using a script like this;
Function PromptForInput(prompt)
Dim prog : prog = WScript.Fullname
If LCase(Right(prog, 12)) = "\cscript.exe" Then
Call WScript.StdOut.WriteLine(prompt & " ")
PromptForInput = WScript.StdIn.ReadLine()
Else
Call Err.Raise(vbObjectError + 5, "Must be called from cscript.exe")
End If
End Function
Dim input
input = PromptForInput("Did you wish to continue? [Y/N]")
Select Case UCase(input)
Case "Y", "N"
Call WScript.StdOut.Writeline("You chose: " & UCase(input))
Case Else
Call WScript.StdOut.Writeline("Invalid option!")
End Select
Output:
Did you wish to continue? [Y/N]
y
You chose: Y
You can adapt it to prompt for passwords but be aware that the input is not hidden so all the characters typed are visible in the command window until it's closed.

How to search by category?

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 & "*'"

Excel - VBA : Userform.Label won't change

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

Resources