Nesting Inputbox If Statements - vb6

This is probably a simple question, but if I need to collect data at the start of a sub, using several input boxes, which one of these is the right way?
Example 1:
InputText1 = InputBox("Enter your name")
If InputText1 = "" Then Exit Sub
InputText2 = InputBox("Enter your age")
If InputText2 = "" Then Exit Sub
'Do something
Example 2:
InputText1 = InputBox("Enter your name")
If Not InputText1 = "" Then
InputText2 = InputBox("Enter your age")
If Not InputText2 = "" Then
'Do something
End If
End If

I think a better way would be to create a form asking for all of the data.
However both your sets of code work. It depends on if you believe that there should only be one exit in a procedure. Your second example only has one exit. The reasoning for that is that you always know where it exits. However the downside is that the code becomes nested and more complex visually. I prefer to exit if he condition is simple and the subroutine is ending with an error exit ie not doing something. SO I would prefer Example 1.

Related item of interest that may not help answer your question:
There is another returned state you can test for: the Cancel button.
Dim InputText1 As String
InputText1 = InputBox("Enter your name")
If StrPtr(InputText1) = 0 Then
MsgBox "*Canceled*"
ElseIf InputText1 = "" Then
MsgBox "*Empty*"
Else
MsgBox InputText1
End If
It may not matter in this case, but it can be useful to tell the difference.

Related

vbscript X and Cancel not doing what they should

im writing a code in vbscript where it will ask the user for input and then run certain files according to the input and i have the else so that it will redo the if else sequence when you type something that isnt an option but when i try to press cancel or the red 'X' it acts as if i have put in an invalid input and goes over the else sequence.
Dim sInput
sInput = InputBox("input")
If sInput = "input1" or sInput = "input2" Then
set shell=createobject("wscript.shell")
shell.run "file.bat"
elseif sInput = "exit" or sInput = "Exit" Then
WScript.Quit
else
name=msgbox (" That is not a valid response",0+16,"ERROR")
set shell=createobject("wscript.shell")
shell.run "input.vbs"
end if
Don't try to restart the script.
Use a loop instead. End the loop when the user entered a valid option, or quit the entire program if requested.
Option Explicit
Dim Shell, input, button
Set Shell = CreateObject("WScript.Shell")
Do
input = InputBox("input")
If IsEmpty(input) Or LCase(input) = "exit" Then WScript.Quit
input = LCase(Trim(input))
If input = "input1" Or input = "input2" Then
Shell.Run "file.bat"
Exit Do
Else
button = MsgBox("That is not a valid response.", vbExclamation + vbRetryCancel, "ERROR")
If button = vbCancel Then Exit Do
End If
Loop
Notes:
Option Explicit makes variable declaration mandatory. It's a good idea to always have this enabled.
IsEmpty() is true when the user pressed the Cancel button (or the Esc key) in the InputBox - but this will work only before the response is manipulated in any way, such as LCase or Trim. Supporting the Cancel button is more intuitive than having a special "exit" keyword, so maybe you should get rid of that.
The various constants you can use with MsgBox are described on ss64.com and in more detal in the official VBScript language reference.
You can change what Enter and Esc do in each MsgBox by using the vbDefaultButton1 or vbDefaultButton2 constants.
The Do loop without any conditions (Do/Loop While ... or Do/Loop Until ...) will run forever - be sure not to forget using Exit Do or WScript.Quit(). (If you do, killing the Script with the Task Manager will get you out of it.)

GoTo "Expected Statement"

I am attempting to use the GoTo command (I do not know any alternatives and it works fine in batch). Whenever I attempt to load the program, I get this error:
Here is basically where the error is (line 11 column 3)
top:
input = InputBox("Enter normal text:", "Message Encrypt Style 2", "Text goes here")
If input = "" Then
Y = MsgBox("You inputed nothing!", vbRetryCancel+64, "Huh?")
If Y = 2 Then
WScript.Quit
Else
If Y = 4 Then
GoTo top
Else
If input = 2 Then
WScript.Quit
VBScript doesn't have a Goto statement, and there's a cleaner approach anyway.
Do
input = InputBox(...)
If IsEmpty(input) Or input = "2" Then
WScript.Quit
ElseIf input = "" Then
MsgBox "No input."
End If
Loop Until input <> ""
try this
Option Explicit
Dim Input ' as string
Dim Y ' as msgbox response
Input = ""
Do Until Input <> ""
Input= InputBox("Enter normal text:", "Message Encrypt Style 2", "Text goes here")
If Input = "" Then
Y = Msgbox ("You input nothing", vbRetryCancel, "Huh?")
If Y = vbCancel Then
WScript.Quit
End If
ElseIf Input = "2" Then
WScript.Quit
End If
Loop
' Proceed here if input is valid
Vbscript is a structured programming language and one of the main goals of structured programming is to eliminate the goto statement as it's considered harmful. Vbscript does have a goto for exceptions, but these are only meant for resource cleanup prior to a program exit.

Validate entry of an input box

Im trying to get an input box to validate the entries a user will make.
i'm using the below script but cant get the validation to work, any help would be appreciated.
Sub inputbox()
Dim Manager As Long
On Error Resume Next
Application.DisplayAlerts = False
Manager = Application.inputbox(Prompt:="Please enter a manager.", Title:="Pick A Manager Name", Type:=1)
On Error GoTo 0
Application.DisplayAlerts = True
If Manager = "" Then
Exit Sub
ElseIf Manager <> Ben, Cameron, Chris, Martin, Peter Then
MsgBox "Incorrect Name, pick a new one!"
Else
MsgBox "Your input was " & Manager
End If
End Sub
Although a Sub name same as built in ones are not recommended, you can do what you are after like below.
First you need to change the InputBox Type to 2 (String), since you are comparing with String. Then you should make a function to check if the input is part of a Manager List.
Sub inputbox()
On Error Resume Next
Dim Manager As String
Manager = Application.inputbox(Prompt:="Please enter a manager name:", Title:="Pick A Manager Name", Type:=2)
If Manager <> "" Then
If IsManager(Manager) Then
MsgBox "Your input was " & Manager
Else
MsgBox "Incorrect Name, pick a new one!"
End If
End If
End Sub
Private Function IsManager(sTxt As String) As Boolean
Dim aManagers As Variant, oItem As Variant, bAns As Boolean
aManagers = Array("Ben", "Cameron", "Chris", "Martin", "Peter")
bAns = False
For Each oItem In aManagers
If LCase(oItem) = LCase(Trim(sTxt)) Then
bAns = True
Exit For
End If
Next
IsManager = bAns
End Function
UPDATE (Improved version suggested by Simon1979):
Private Function IsManager(sTxt As String) As Boolean
On Error Resume Next
Dim aManagers As Variant
aManagers = Array("Ben", "Cameron", "Chris", "Martin", "Peter")
IsManager = Not IsError(Application.WorksheetFunction.Match(Trim(sTxt), aManagers, 0))
End Function
Haven't used the InputBox with Excel but I imagine it will be very similar to the Access one. I use the below method to validate inputbox:
Dim strM as string
EnterManager:
strM = InputBox("Enter Manager.")
If StrPtr(strM) = 0 Then 'Cancel was pressed
' Handle what to do if cancel pressed
Exit Sub
ElseIf Len(strM) = 0 Then 'OK was pressed with nothing entered
MsgBox "You must enter a Manager."
GoTo EnterBuyer
End If
To add your criteria you could add on another If, I'm not sure you can use the approach you have for checking the list of names. Also don't understand how you compare a long Manager with a list of names Ben, Cameron, Chris, Martin, Peter, unless they are assigned variables, in which case I would suggest adding prefixes so it is more obvious such as lBen as opposed to strBen so you can easily see the difference in variable type.
If strM <> "Ben" And strM <> "Cameron" And strM <> "Chris" And strM <> _
"Martin" And strM <> "Peter" Then
MsgBox "Incorrect Name, pick a new one!"
Else
MsgBox "Your input was " & strM
End If

Yes/no shut down

I am playing with VBScript and I want to make a MsgBox which asks the user if they want to shut down their computer or not.
If the user clicks Yes they should see a MsgBox first then their computer starts to shutdown.
I am using this code but it doesn't work.
What is the problem?
result = MsgBox ("Shutdown?", vbYesNo, "Yes/No Exm")
Select Case result
Case vbYes
MsgBox("shuting down ...")
Option Explicit
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 0"
Case vbNo
MsgBox("Ok")
End Select
I have amended your code as per below:
Option Explicit
Dim result
result = MsgBox ("Shutdown?", vbYesNo, "Yes/No Exm")
Select Case result
Case vbYes
MsgBox("shuting down ...")
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 20"
Case vbNo
MsgBox("Ok")
End Select
The main issues were that "option explicit" has to be at the top, and as a result the "result" variable then must be declared using the "dim" keyword. The above code works fine when I executed it via the command line.
I also added a timeout of 20, but you can easily change this back to the original value of 0.
As documented Option Explicit must appear before any other statement in a script. Using it anywhere else in a script should raise a "Expected Statement" error pointing to the line with the Option Explicit statement. If you don't get that error, you have an On Error Resume Next in your code that you didn't show.
If you move the Option Explicit statement to the beginning of the script, but the shutdown still doesn't occur, you need to check the return value of the shutdown command:
rc = objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 0", 0, True
If rc <> 0 Then MsgBox "shutdown failed with exit code " & rc & "."
The parentheses in your MsgBox statements shouldn't cause an issue as long as you pass just a single argument to the function, but I'd still remove them.
Try This:
Set Shell = CreateObject("WScript.Shell")
Answer = MsgBox("Do You Want To" & vbNewLine & "Shut Down Your Computer?",vbYesNo,"Shutdown:")
If Answer = vbYes Then
Shell.run "shutdown.exe -s -t 60"
Ending = 1
ElseIf Answer = vbNo Then
Stopping = MsgBox("Do You Wish To Quit?",vbYesNo,"Quit:")
If Stopping = vbYes Then
WScript.Quit 0
End If
End If

Control Properties in Visual Basic 6

Is there a way to ask for a control property in a loop??
I need somethig like this:
For each p in control.properties
if p = "Value" then
msgbox "I Have Value Property"
elseif p = "Caption" then
msgbox "I Have Caption Property"
end if
next
It could be done somehow?
Found this code on Experts Exchange. Add a reference to TypeLib Information.
Public Enum EPType
ReadableProperties = 2
WriteableProperties = 4
End Enum
Public Function EnumerateProperties(pObject As Object, pType As EPType) As Variant
Dim rArray() As String
Dim iVal As Long
Dim TypeLib As TLI.InterfaceInfo
Dim Prop As TLI.MemberInfo
On Error Resume Next
ReDim rArray(0) As String
Set TypeLib = TLI.InterfaceInfoFromObject(pObject)
For Each Prop In TypeLib.Members
If Prop.InvokeKind = pType Then
iVal = UBound(rArray)
rArray(iVal) = UCase$(Prop.Name)
ReDim Preserve rArray(iVal + 1) As String
End If
Next
ReDim Preserve rArray(UBound(rArray) - 1) As String
EnumerateProperties = rArray
End Function
You can ask for a list of the readable, or writeable properties.
Bonus, ask if a specific property exists.
Public Function DoesPropertyExist(pObject As Object, ByVal _
PropertyName As String, pType As EPType) As Boolean
Dim Item As Variant
PropertyName = UCase$(PropertyName)
For Each Item In EnumerateProperties(pObject, pType)
If Item = PropertyName Then
DoesPropertyExist = True
Exit For
End If
Next
End Function
Beaner has given an excellent direct answer to the question you have asked.
I'm guessing what you might be trying to do. Perhaps you're trying to get the "text" from a control but you don't know the type of the control at runtime. You could consider something like this, which tries a number of hard-coded property names in turn until something works.
Function sGetSomeText(ctl As Object) As String
On Error Resume Next
sGetSomeText = ctl.Text
If Err = 0 Then Exit Function
sGetSomeText = ctl.Caption
If Err = 0 Then Exit Function
sGetSomeText = ctl.Value
If Err = 0 Then Exit Function
sGetSomeText = "" 'Nothing worked '
End Function
Another approach would be to check the type of the control at runtime. You can use
If TypeName(ctl) = "whatever" or
If TypeOf ctl Is whatever.
Then you could switch to code for specific control types that definitely have the Text property, etc.
I'm not sure what you're hoping to accomplish, but I'm pretty sure VB6 does not support what you're talking about. You could try something like this:
If control.Value Is Not Nothing Then
msgbox "I Have Value Property"
Else If control.Caption Is Not Nothing Then
msgbox "I Have Caption Property"
See if that accomplishes what you're looking to do.

Resources