I have created an Inputbox to get the username entered but stuck with the cancel button
Private Sub Form_Load()
fsUserName = UCase(InputBox("Please Enter your name.", "User Name", _
"dc"))
If fsUserName = "" Then
MsgBox "No name Entered." & Chr(13) & Chr(13) & _
"You must enter a name.", vbExclamation, "ERROR"
Form_Load
ElseIf VarType(fsUserName) = 0 Then 'If cancel clicked
cmdQuit_Click
End If
Also is there a way that when the X button on the form is clicked it executes cmdQuit_Click so that if the userclicks the command button Quit or X ,the Quit script is run.In the quit script there are message boxes and cleanup.
You can use StrPtr() to detect if cancel was clicked;
Dim fsUserName As String
fsUserName = InputBox("Please Enter your name.", "User Name", "dc")
If (StrPtr(fsUserName) = 0&) Then
MsgBox "Cancelled or X clicked"
ElseIf fsUserName = "" Then
MsgBox "No name Entered." & vbCr & "You must enter a name.", vbExclamation, "ERROR"
Else
fsUserName = UCase$(fsUserName)
MsgBox fsUserName
End If
If you want to do something when the form unloads you can use the Form_Unload event or better the Form_QueryUnload event which fires before the actual unload & allows you to cancel it.
It will also tell you why the form is unloading (UnloadMode will be 0 if the red X is clicked)
Using "Unload Me" will raise both of the events.
Edit: Calling Form_Load in Form_Load like that will eventually fill up the stack, better to use a loop to look for a missing username.
Alex's answer using StrPtr, which I assume works as advertised, is good as far as it goes, but the better advice (IMO) is to avoid InputBox altogether. You can easily create your own using a dialog-style form, a textbox, and a couple of buttons, and maybe an icon if you like.
Rolling your own gives you complete flexibility and predictability, and once you have it you can use it in any future projects.
Excel InputBox and Application.InputBox are different functions.
Sub GetValue2()
Dim Monthly As Variant
Monthly = Application.InputBox _
(Prompt:="Podaj wysokość miesięcznej wypłaty:", _
Type:=1)
If Monthly = False Then Exit Sub
MsgBox "Zarobki rocznie: " & Monthly * 12
End Sub
Try this...
Name = Application.InputBox("Please enter Name")
If Name = "False" Then
MsgBox " Your message here"
Exit Sub
End If
Related
I am trying to make the cancel function work for my array it works for a simple input box but Array(InputBox( does not like it very much.
Working code.
If strVarValue = vbNullString Then
MsgBox ("User canceled!")
WScript.Quit
End If
What I need help with
strIPAddress = Array(InputBox("IP address"))
If strIPAddress = vbNullString Then
MsgBox ("User canceled!")
WScript.Quit
End If
Doesn't like the Array hence why I'm getting type mismatch.
Do the conversion only if the user did not press "Cancel":
userInput = InputBox("IP address")
If userInput = "" Then
MsgBox ("User canceled!")
WScript.Quit
End If
strIPAddress = Array(userInput)
Also, if you want to distinguish between "user pressed Cancel" and "user pressed OK without entering a value" you need to check if the variable is Empty:
userInput = InputBox("IP address")
If IsEmpty(userInput) Then
MsgBox ("User canceled!")
WScript.Quit
ElseIf userInput = "" Then
MsgBox ("Missing input!")
WScript.Quit 1
End If
strIPAddress = Array(userInput)
I am using the script listed below (I honestly stole this probably from this very site) for a browse button on a form. The task is simply to start up MS File Dialog box so that a file (in this case an image file) can be selected. Once you select the record and click ok it then pastes the file name and location into a field.
Viewing the table the file name and location is pasted just as it should be. The problem comes in with a report I built. I have an image set to display with the control source linked back to that file address field. It will not display the image though.
However, if I manually type the same address character for character or even “copy”, delete, and then “paste” the same exact entry into the field the image then displays just fine on the report.
I have checked to make sure there are no spaces or characters anywhere there shouldn’t be. I am at a loss here.
Any help would be greatly appreciated and I will gladly give you my first born. Ok maybe not the first I like him but you can have the second one, she’s hell.
Private Sub Command67_Click()
On Error GoTo SubError
'Add "Microsoft Office 14.0 Object Library" in references
Const msoFileDialogFilePicker As Long = 3
'Dim FD As Office.FileDialog
Dim FDialog As Object
Dim varfile As Variant
Set FDialog = Application.FileDialog(msoFileDialogFilePicker)
EmployeePicture = ""
' Set up the File Dialog
Set FDialog = Application.FileDialog(msoFileDialogFilePicker)
With FDialog
.Title = "Choose the spreadsheet you would like to import"
.AllowMultiSelect = False
.InitialFileName = "C:\Users\" 'Folder picker needs trailing slash
.Filters.Clear
.Filters.Add "All", "*.*"
If .Show = True Then
If .SelectedItems.Count = 0 Then
'User clicked open but didn't select a file
GoTo SubExit
End If
'An option for MultiSelect = False
'varFile = .SelectedItems(1)
'EmployeePicture = varFile
'Needed when MultiSelect = True
For Each varfile In .SelectedItems
EmployeePicture = EmployeePicture & varfile & vbCrLf
Next
Else
'user cancelled dialog without choosing!
'Do you need to react?
End If
End With
SubExit:
On Error Resume Next
Set FDialog = Nothing
Exit Sub
SubError:
MsgBox "Error Number: " & Err.Number & " = " & Err.Description, vbCritical + vbOKOnly, _
"An error occurred"
GoTo SubExit
End Sub
I have this file that makes a computer say something. I want it to loop with a VbCancel function. I get this error. Code so far:
Do
Dim Message, Speak
Message=InputBox("Enter text","Speak")
Set Speak=CreateObject("sapi.spvoice")
MsgBox ("You entered: " & Speak)
Speak.Speak Message
If Len(Speak) = 0 Then
MyMessageBox = MsgBox("Click Yes if you mean to Cancel." & vbCrLf & _
"If you mean to enter a zero length string, click No.", vbYesNo, "DO YOU MEAN TO CANCEL?")
If MyMessageBox = vbYes Then
MsgBox "Operation Cancelled"
Exit Sub
End If
Loop
BTW the error is Invalid exit statement
I'm working on Windows 7
Dim Message, Speak
Do
Message=InputBox("Enter text","Speak")
Set Speak=CreateObject("sapi.spvoice")
MsgBox ("You entered: " & Message)
Speak.Speak Message
If Len(Message) = 0 Then
MyMessageBox = MsgBox("Click Yes if you mean to Cancel." & vbCrLf & _
"If you mean to enter a zero length string, click No.", vbYesNo, "DO YOU MEAN TO CANCEL?")
If MyMessageBox = vbYes Then
MsgBox "Operation Cancelled"
Exit Do
End If
End If
Loop
You had several issues here
Exit Sub is for subroutines. You were trying to exit a Do loop
Speak is an object. I dont know if it has a string property but it is not itself a string. Both Len(Speak) and "You entered: " & Speak has Speak changed to Message.
You were missing an End If
I moved the Dim statements out of the loop. No point recreating the object over and over again.
Dim Message, Speak
Do
Message=InputBox("Enter text","Speak")
Set Speak=CreateObject("sapi.spvoice")
MsgBox ("You entered: " & Message)
Speak.Speak Message
If Len(Message) = 0 Then
MyMessageBox = MsgBox("Click Yes if you mean to Cancel." & vbCrLf & _
"If you mean to enter a zero length string, click No.", vbYesNo, "DO YOU MEAN TO CANCEL?")
If MyMessageBox = vbYes Then
MsgBox "Operation Cancelled"
Exit Do
End If
End If
Loop
How do you display a message in VBScript?
This results in an error message:
X = MsgBox("Something, Happy Fools!", 0+16, "Ha!")
That message was just an error one. How can I fix it?
There are quite a few msgbox types out there...
Here are some links:
1: VBA Message Box (msgbox) – The Message Can Do Better
2: VBA Message Box Function
3: VBScript Message Box Function
Here's the syntax:
Syntax
MsgBox(prompt[, buttons] [, title] [, helpfile, context])
And here's some examples:
'basic
Sub basic_messagebox()
MsgBox "Hi there"
End Sub
'Abort/Retry/Ignore - returns integer according to user entry.
Sub basic_messagebox()
i = MsgBox("Do you wish to be terminated ?", vbAbortRetryIgnore, "Greetings Earthlings", "test.hlp", 100)
End Sub
'Yes No msgbox
Sub YesNo_msgbox
intAnswer = Msgbox("Do you want to delete these files?", vbYesNo, "Delete Files")
If intAnswer = vbYes Then
Msgbox "You answered yes."
Else
Msgbox "You answered no."
End If
End Sub
'You can incrementally add on different vbelements to build the msgbox construct
Sub basic_messagebox()
i = MsgBox("Hi there", vbOKOnly + vbCritical)
End Sub
And here's a list of accepted vb elements in a msgbox.
The MsgBox method is precisely how you accomplish it in VBScript. Use either of these syntax varieties:
msgbox "hello", 0+16, "foo"
or
call msgbox("hello", 0+16, "foo")
Hi Hi I have to write a code where if the user clicks enters something in the input box it should proceed further.If it doesnot enter any value it should throw back the same question again again.This i have already achieved,but my problem is when user click on CANCEl it agains asks the same question whereas it ishould exit .I am very new to VB Script .Plz help me how to handle these buttons?Below is my existing code
Do while x=0
strAnswer = InputBox("Please enter the file extension * For all files:", _
"File Extension")
If strAnswer = "" Then
MsgBox"You must enter an extension."
Else
a=strAnswer
Exit Do
End If
Loop
intRow = 2
'strFileName = "T:\public\Madhumita\New.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
'objWorkbook.SaveAs(strFileName)
objExcel.Cells(1, 1).Value = "Folder"
objExcel.Cells(1, 2).Value = "File Name"
objStartFolder = "T:\public\Madhumita\Madhu"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
If a="*" Then
For Each objFile in colFiles
objExcel.Cells(intRow, 1).Value = objfolder.Name
objExcel.Cells(intRow, 2).Value = objFile.Name
intRow = intRow + 1
Next
else
For Each objFile in colFiles
m=objFSO.GetExtensionName( objFile.Path )
If m=a Then
objExcel.Cells(intRow, 1).Value = objfolder.Name
objExcel.Cells(intRow, 2).Value = objFile.Name
intRow = intRow + 1
End If
Next
End If
objExcel.Range("A1:B1").Select
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit
Sub SaveAs()
Application.Dialogs(xlDialogSaveAs).Show
End Sub
objExcel.Quit
MsgBox "Done"
You need to deal with (at least) three cases - InputBox() returns:
an empty value (Empty, vbEmpty) because the user pressed Cancel or closed the dialog
an empty string ("") or a string of blanks (" ")
a (hopefully) valid string
In code:
Option Explicit
Do While True
Dim vInp : vInp = InputBox("ee")
WScript.Echo TypeName(vInp)
Select Case True
Case IsEmpty(vInp)
WScript.Echo "Abort"
Exit Do
Case "" = Trim(vInp)
WScript.Echo "Try again"
Case Else
WScript.Echo "Work with " & vInp
Exit Do
End Select
Loop
sample output:
String
Try again
Empty
Abort
String
Work with aaa
Sorry to say, but the Docs just lie:
If the user clicks OK or presses ENTER, the InputBox function returns
whatever is in the text box. If the user clicks Cancel, the function
returns a zero-length string ("").
It should be:
... If the user clicks Cancel, the function returns an empty value
(TypeName Empty, VarType vbEmpty).
For InputBox(), you can use the default value to determine if the user clicked Cancel or if they clicked OK or hit Enter to continue without entering a value:
Sub Get_TIN()
TIN = Trim(InputBox("Enter the provider TIN:", "Provider TIN", "ex. 123456789"))
If TIN = "" Then 'When CANCEL is clicked because "TIN" will be empty.
MsgBox "You pressed Cancel. Program will now end.", vbExclamation + vbOKOnly, "Macro End"
Exit Sub
End If
If IsEmpty(TIN) = False Then 'When OK is clicked or Enter pressed because default text will be stored. Next, set TIN to "".
TIN = ""
End If
End Sub
I'm using VBS and my investigation into cancel/ok revealed the following:
Cancel returns an empty string AND a zero length string - same thing you say?, apparently not.
Ok returns a zero length string only.
I use the code below to differentiate.
if IsEmpty(nmbr) then 'cancel button pressed ?
nmbr = "x"
end if
if not IsEmpty(nmbr) then 'ok button pressed ?
if len(nmbr) = 0 then
nmbr = "ok"
end if
end if