This is in vbscript on an .asp page.
number1 = GETFIELDSFROMSQL(sqlRequest, "MaxLoan")
response.write "number1: " & number1
response.write "number2: " & Session("number2")
If number1 > Session("number2") Then
response.write "TESTTTTTTTT entered the if statement!"
number1 = Session("number2")
End If
number 1 prints to the screen as 10000
number 2 prints to the screen as 30000
But for some reason, it's entering the if statement and I don't think it should.
What are some reasons vbscript might enter a false if statement?
If the datatype for number1 is an int and Session("number2") is a string then the expression can give the wrong result.
Related
I'm trying to read a recordset from SQL database were some field are of type time(n).
When I read a row (recordset.Fields(n)), VBScript stops at this field with a 'multiple step error'.
I tried to set a variable with the recordset, so:
Dim a
Set a = recordset.Fields(specific time column)
I tried to cast the field.
I tried to find any information about this specific type, but I can't find any information about this time structure, besides it contains hour, minute, second and fractional parts.
ReDim iArr(iColumnCount)
While Not objRecordset.EOF
For iColumnIndex = 0 To (iColumnCount-1)
'SQL_FIELDTYPE_TIME is a constant at top of page with value 145
If objRecordset.Fields(iColumnIndex).Type = SQL_FIELDTYPE_TIME Then
'Tried so much over here...
Dim Tme, Str
Set Tme = objRecordset.Fields.Item(iColumnIndex)
iArr(iColumnIndex) = CStr(clDBTime(Tme).Hour)
Set Tme = Nothing
Else
iArr(iColumnIndex) = objRecordset.Fields.Item(iColumnIndex)
End If
If Err.Number <> 0 Then
fLogData("Ophalen data (" + oDB.strDatabaseNaam + ") rij " + _
CStr(objRecordset.AbsolutePosition) + " kolom " + _
CStr(iColumnIndex) + " mislukt: " + Err.Description)
Err.Clear
End If
Next
List.Add i, iArr
i = i + 1
objRecordset.MoveNext 'Next row
Wend
Errors I'm getting:
Object doesn't support this property
Multiple step error
Type mismatch
etc. etc.
Anyone who can help me out how to read the time value from SQL in VBScript?
EDIT: solved! Cost almost 4h trial-error but there's a solution:)
Changed the SQL select statement to:
SELECT COL, COL,... (this are the 'usual' columns),CAST(TIMECOL -this is the time(n) column- as varchar),CAST(TIMECOL2 -this is the time(n) column- as varchar) FROM tabel
And within code: TimeValue(read value - from recordset.fields...) (this is to change varchar back to time)
And .. it just works great!
Edit2: recordset code:
if iResCount > 0 and iColumnCount > 0 then
redim iArr(iColumnCount)
while not objRecordset.EOF
for iColumnIndex = 0 to (iColumnCount-1)
iArr(iColumnIndex) = objRecordset.Fields.Item(iColumnIndex)
if Err.Number <> 0 then
fLogData("Ophalen data ("+oDB.strDatabaseNaam+") rij "+cstr(objRecordset.AbsolutePosition)+ " kolom "+cstr(iColumnIndex)+" mislukt: "+Err.Description)
Err.Clear
end if
next
List.Add i, iArr
i = i + 1
objRecordset.MoveNext 'Next row
wend
set oResult = List'CreateObject("Scripting.Dictionary")
end if
And an example of a function call:
'fGetRecord(DB, Table, Columns, Condition, Field to sort on, Type of sort)
fGetRecord(oHoofdDB,CONST_HDB_STR_TBL_KALENDER,CONST_HDB_STR_KAL_ID+","+CONST_HDB_STR_KAL_NAAM+",CAST("+CONST_HDB_STR_KAL_STARTIJD+" as varchar),CAST("+CONST_HDB_STR_KAL_STOPTIJD+" as varchar)",CONST_HDB_STR_KAL_NAAM+"='"+Naam+"'", "", SORTEER_OPLOPEND)
John
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.
Hy I am new to programming vbscript.I am trying to make a textbox for user in which user has to enter file version(format 1,0,0,0).user must type one integer within commas.but I failed to make a validation script to do so.. Can you please help me. Thanks in advance.I have been created this script to perform other kind of validation but I don't know how to do the validation for x,y,z,h format..
Do
dtm = InputBox("Please Enter a Numeric File version using commas", _
"File version")
Select Case True
Case isNull(dtm), (not isNumeric(dtm)), dtm = "", dtm = empty, (dtm < 1 OR dtm > 9)
MsgBox "Please enter between 1 and 9"
Case else
Exit do
End Select
Loop While True
'script on test pass
Something like this should do the job (have not tested with wscript/cscript), assuming accepted numbers are 0 to 9.
Function GetVersionNumber() As String
Dim iParts, sVersion, oTmp, dtm
iParts = 0
sVersion = ""
Do
dtm = InputBox("Please Enter a Numeric File version using commas", "File version")
For Each oTmp In Split(dtm, ",")
If IsNumeric(Trim(oTmp)) Then
If Len(sVersion) > 0 Then sVersion = sVersion & ","
sVersion = sVersion & Trim(oTmp)
iParts = iParts + 1
Else
MsgBox "Please enter between 0 and 9!" & vbCrLf & "You have typed " & oTmp
iParts = 0 ' Reset to zero accepted parts
sVersion = "" ' Reset to zero length string
End If
Next
Loop Until iParts = 4 ' x,y,z,h format <- 4 parts
GetVersionNumber = sVersion
End Function
I need a VBScript loop asking to entered an integer between 1 to 10 including, if wrong symbol or number entered then asking again until the desired number is retrieved from user.
This is what I tried:
Option Explicit
Dim Num
Num=inputbox("Please enter integer number between 1 to 10")
'Checking if entered value is numeric
Do while not isnumeric(Num)
Num=inputbox("Please enter integer number between 1 to 10", "INCORRECT SYMBOL")
Loop
Do while (Num<1 or Num>10)
Num=inputbox("Please enter integer number between 1 to 10 ", "Number is NOT IN RANGE")
Loop
Do while not int(Num)
Num=inputbox("Please enter integer number between 1 to 10 ", "Number is NOT INTEGER")
Loop
does not work: when I enter 3 for example I am getting inputbox saying "Number is NOT INTEGER", when entering a letter I receive error message Type mismatch string, error code 800A00D.
You need one Loop. For each (variant) input you need to check:
is it Empty (User pressed Cancel or X) - Abort
is it a blank (zero length or sequence of spaces) string
is it numeric
is it an integer
is it in range - Accept
As in:
Option Explicit
Dim vNum, sNum, nNum
Do
vNum = InputBox("Please enter an integer beween 1 and 10 (inclusive)")
If IsEmpty(vNum) Then
WScript.Echo "Aborted"
Exit Do
Else
sNum = Trim(vNum)
If "" = sNum Then
WScript.Echo "Empty string"
Else
If IsNumeric(sNum) Then
nNum = CDbl(sNum)
If nNum <> Fix(nNum) Then
WScript.Echo "Not an Integer"
Else
If nNum < 1 Or nNum > 10 Then
WScript.Echo "Not in range"
Else
WScript.Echo nNum, "is ok"
Exit Do
End If
End If
Else
WScript.Echo "Not a number"
End If
End If
End If
Loop
WScript.Echo "Done"
Using different variables for the different data types may be pedantic, but should show why you had type problems.
Your
Do while not int(Num)
does not work as expected because here Num is a number between 1 and 10; rounding off the (not existing) fractional part gives Num again; Num evaluated in a boolean context/as a bool gives (always) True.
Update wrt comment:
Trim removes space from the head or tail of a string; WScript.Echo sends output to the console (cscript) or a dialog box (wscript).
Update:
As this question shows, I didn't make clear that pressing Cancel or X (Close) sets vNum to an empty variant, which is different from an empty/zero length string. So it should be treated as indication of the users intention to abort.
BTW: You need to read the Docs, but you can't believe them always (cf. here).
DISCLAIMER: I'm still an uber-n00b with programming concepts and know just enough VBS to hurt myself, so I'm likely to slur/slaughter some of the terms/concepts/ideas that are entailed with this program I'm trying to write. You, the vastly superior programmer who has every right to flame me, have been warned.
I've been trying to write a VBScript to validate data, specifically Dates. Since my users are kind of poor with keyboards, I figured I'd make it easy by separating the entry of each part of the date (Month & Day only, I've got the Year set statically).
Previously, I was having problems with validating the numbers with only 1 "Do...Loop", as I was trying to verify if it was Numeric Input and checking at the same time if it was within the specified range (1 - 12, for the 12 months of the year).
This is what the previous code roughly looked like:
Do
' If...Then Statements Here
Loop Until (dtFirstMonth > 0) _
And (dtFirstMonth < 13) _
And IsNumeric(dtFirstMonth) _
And (dtFirstMonth <> "") _
And (dtFirstMonth <> vbNull)
This often resulted in "Data Type Mismatch" errors, so I had to split the Validation Critera to two separate "Do...Loop" statements, as you can see in the current code I have below:
Sub srTest()
Do
dtFirstMonth = InputBox("Please Enter a Numeric Month for the Starting Range", _
"Starting Range Month")
If (dtFirstMonth = vbNull) _
Or (dtFirstMonth = "") _
Or Not IsNumeric(dtFirstMonth) Then
MsgBox "Please Enter a Valid Numeric Month",, "Enter Month Number"
ElseIf (dtFirstMonth <> vbNull) _
And (dtFirstMonth <> "") _
And IsNumeric(dtFirstMonth) Then
Do
dtFirstMonth = Round(dtFirstMonth)
Wscript.Echo dtFirstMonth ' Infinite Loop Here (Basically, As Soon As We Get Into Loop with a Value of 1, We're Stuck)
dtFirstMonth = CInt(dtFirstMonth)
' Must Convert User Input to Integer to
' Prevent Data Mismatch Errors In
' Following "If" Statement; Besides,
' It Passed the First Test to be a
' Numeric Value in the First Place
If (dtFirstMonth < 1) Or (dtFirstMonth > 12) Then
MsgBox "Please Enter a Valid Numeric Month",, "Enter Month Number"
Exit Do
' Drop Out of 2nd Level Loop to
' Enter Into 1st Level Loop
End If
Loop Until (dtFirstMonth > 0) _
And (dtFirstMonth < 13) _
And IsNumeric(dtFirstMonth) _
And (dtFirstMonth <> "") _
And (dtFirstMonth <> vbNull)
If (dtFirstMonth < 1) Or (dtFirstMonth > 12) Then
dtFirstMonth = ""
End If
' dtFirstMonth Was Converted to Integer Earlier
' This is to Meet the Value that Didn't Pass
' the Nested Do & If Statement (Level 2 Do Loop)
' Sets dtFirstMonth to "Empty String" to Continue
' Looping in the Level 1 "Do...Loop" Statement;
' If Omitted, Level 1 "Do...Loop" is Satisfied,
' Thus Ending the Subroutine (Since the Value
' of dtFirstMonth is Still a Numeric Value)
End If
Loop Until IsNumeric(dtFirstMonth) _
And (dtFirstMonth <> "") _
And (dtFirstMonth <> vbNull)
Wscript.Echo dtFirstMonth
End Sub
srTest
I had to set up the 1st "Do...Loop" to check that the User Input (dtFirstMonth) was a indeed a Numeric Value and not a Null Value nor an Empty String. The Nested "Do...Loop", or 2nd "Do...Loop", statement is where I have the same Criteria plus the extra Criteria defining the desired ranges (any number between 1 and 12).
This is working perfectly for number 2-12, but when the script parses the number 1, I enter into an Infinite Loop.
I've checked to make sure that the Infinite Loop is occurring in the 2nd "Do...Loop" by replacing the entire 2nd "Do...Loop" section with "Wscript.Echo dtFirstMonth". By doing this, I get the expected results: a single Echo, not an infinite number of them (technically, I get 2, as I do have another "Wscript.Echo dtFirstMonth" string at the bottom of the Subroutine for the purpose of debugging, but either way, it's not an Infinite Loop).
I've also changed the criterion for the lower range to be like this, yet this doesn't remediate the error:
Do
' If...Then Statements Here
Loop Until (dtFirstMonth >= 1)
I've also tried this, with no resulting success:
Do
' If...Then Statements Here
Loop Until (dtFirstMonth >= CInt(1))
In all reality, there really is no need for this segment, since I converted the User's Input to an integer anyway.
Since this was starting to get confusing, I decided to add the "Round" statement before the script passed the User's Input to the "CInt" function, hoping that it would make sure that it wasn't getting caught as a 0 value or decimal value somehow; yes, this is irrational thought on my part, but I still wanted to explore all avenues (there's also the fact that I have some users with "Fat Finger Syndrome" and some others with "Abuse The Program" mentality, so I figured I'd make sure the script accounted for decimal entries). I added the "Round" string before and after the nested "Do...Loop" and I still had the Infinite Loop issue.
This is as far as I've been able to get on this and now I'm stuck.
I realize that there are likely better ways to do Date/Time Validation in VBScript, and I'm certainly open to any new suggestions, but I'd love to solve this for the pure sake of edification.
Way too much code for a simple input of a number. Just try to keep it short and simple. Example:
Do
dtm = InputBox("Please Enter a Numeric Month for the Starting Range", _
"Starting Range Month")
Select Case True
Case isNull(dtm), (not isNumeric(dtm)), dtm = "", dtm = empty, (dtm < 1 OR dtm > 12)
' too exhaustive, but just for the sake of the example.
MsgBox "Please enter an amount between 1 and 12"
Case else
' Hey, this seems to be a valid amount!
Exit do
End Select
Loop While True
' Do something with dtm
Just showed you some creative Select Casing, this supports lazy exit, so if a value is Null, it escapes before getting evaluated where evaluating could throw an error.
The problem is with your attempt to check for null values:
(dtFirstMonth = vbNull)
The proper way to check for nulls, as demonstrated in AutomatedChaos' answer, is with the IsNull function. vbNull is actually a constant that's used with the VarType function. The value of vbNull is 1, which is why that particular value behaved differently from other entries. That's the fundamental problem, and if you replace every dtFirstMonth = vbNull with IsNull(dtFirstMonth), you won't get an infinite loop when entering 1.
Now, the actual place where your code infinitely loops is interesting. I would expect the first conditional If (dtFirstMonth = vbNull) to evalute true for an entry of "1", and you would get the message box "Please enter a valid numeric month". However, the Else condition is triggered. This is weird because normally, when you compare a string to a number, VBScript will attempt to convert the number to a string or vice versa, so if dtFirstMonth is "1", it should be equal to vbNull (which is 1). However, there appears to be a special case when you compare a string variable to an integer variable. See this example:
' vbNull = 1, built-in constant
dtFirstMonth = "1"
MsgBox (dtFirstMonth = vbNull) ' False
MsgBox ("1" = vbNull) ' True
MsgBox (dtFirstMonth = 1) ' True
MsgBox (CInt(dtFirstMonth) = vbNull) ' True
I don't know if this is a bug or just an obscure detail about VBScript's implicit conversion, but it does illustrate that implicit conversion can be unpredictable in VBScript.
As far as alternative methods go, you may be interested in the IsDate function, which returns True if the given expression can be converted into a date. It may not be ideal for your users and their keyboard skills, but it would reduce your code to:
Do
str = InputBox("Enter a date (MM/DD)")
If IsDate(str) Then
Exit Do
Else
WScript.Echo "Please enter a valid date"
End If
Loop
dt = CDate(str)
' Put your static year here; CDate will default to the current year
dtActual = DateSerial(2007, Month(dt), Day(dt))
WScript.Echo (dtActual) & " - Thanks!"
Note that IsDate should return False for the typical edge cases ("", Null, Empty, etc.), so there's no need for a separate check.
I found a simple program to generate Date and time from http://rindovincent.blogspot.com/p/vbscript-programs.html. I am pasting the same program with permission.
<html>
<body>
<center>
<script type="text/vbscript">
d=CDate("October 22, 2010")
document.write(d&"<br/>")
document.write("Current system date is:"&date&"<br/>")
document.write("Current system time is:"&time&"<br/>")
document.write(DatePart("m",Now())&"<br/>")
document.write(DateAdd("yyyy",1,"31-Jan-10") & "<br />")
document.write(MonthName(10,true)& "<br />")
fromDate="22-sep-10 00:00:00"
toDate="21-oct-10 23:59:00"
document.write(DateDiff("m",fromDate,toDate)&"<br />")
document.write(DateDiff("y",fromDate,toDate) & "<br />")
document.write(DateDiff("w",fromDate,toDate) & "<br />")
document.write(DateDiff("h",fromDate,toDate) & "<br />")
</script>
</center>
</body>
</html>