What is wrong with VB str() function? - vb6

The abnormal behaviuor of the str() or val() functions made my days horrible, the following bug get me 2 days to find it.
temp = Val(currentYear)
temp = temp + 1
nextYear = Str(temp)
MsgBox "YY" & currentYear & "YY"
MsgBox "YY" & nextYear & "YY"
The initial value of currentYear is "2010"
The result should be:
YY2010YY
YY2011YY
however, the result is:
YY2010YY
YY 2011YY
This bug is gross.After that, I add a line next to my code:
temp = Val(currentYear)
temp = temp + 1
nextYear = Str(temp)
nextYear = LTrim(nextYear)
MsgBox "YY" & currentYear & "YY"
MsgBox "YY" & nextYear & "YY"
Then the result come as expected. Can anyone explain this? Thanks.

You should use CStr instead.
Str uses a space to indicate it is positive, while CStr does not.

Related

Microsoft VBScript runtime error '800a000d' Type mismatch: 'LastID'

I do a function to assign an ID. But when I click button, this error comes out.
Microsoft VBScript runtime error '800a000d' Type mismatch: 'LastID'
Public function AssignSanctionID(DeptID,SectID,SanctionType)
REM obtain Transaction ID
dim CmdX
dim SQLX
dim RsX
dim Prefix
dim LastID
dim CurrID
dim NewCurrID
'- Set Connection
HariNi=now()
Tahun=year(HariNi)
Bulan=month(HariNi)
if len(bulan)=1 then
Bulan= "0" & Bulan
end if
If Cint(Tahun) < 2016 then
Pref1= DeptID & "/" & SectID & "/"
Prefix=DeptID & "/" & SectID & "/" & Tahun & "/" & Bulan & "/"
else
Pref1= DeptID & "/%/" & SectID
Prefix=DeptID & "/" & Tahun & "/" & Bulan & "/"
end if
set CmdX = server.CreateObject("ADODB.Command")
Set RSX = Server.CreateObject("ADODB.Recordset")
SQLX = " SELECT * FROM Sanction " _
& " WHERE SanctionID like '%" & Pref1 & "%' " _
& " ORDER BY ID DESC"
CmdX.ActiveConnection = objconn
CmdX.CommandText = SQLX
RsX.Open CmdX,,0,1
if not(RsX.BOF and RsX.EOF) then
If Cint(Tahun) < 2016 then
LastID = right(RsX("ID"),4)
else
LastID = mid(RsX("ID"),13,4)
end if
else
if Bulan="04" then
LastID=0
end if
end if
RsX.Close
set RsX = nothing
'Set ID
If LastID<>"" then
'CurrID = left(4)
CurrID=int(LastID)+1
end if
if len(currid)>0 then
select case len(currid)
case 1
newcurrid = "000" & currid
case 2
newcurrid = "00" & currid
case 3
newcurrid = "0" & currid
case 4
newcurrid = currid
end select
else
NewCurrID="0001"
end if
If Cint(Tahun) < 2016 then
NewCurrID=Prefix & NewCurrID
else
NewCurrID=Prefix & NewCurrID & "/" & SectID
end if
AssignSanctionID = NewCurrID
end function
Hard to help if I don't see the data.
From quick view of the code the issue is here:
CurrID=int(LastID)+1
You are trying to cast LastID but are you sure that it is convertible? Could list all possible values?
Short answer: CInt only works with Numerical values. If you have letters in your value, then Cint wont work.
Bit longer answer:
Having read the Blog that we should be more welcoming (https://stackoverflow.blog/2018/04/26/stack-overflow-isnt-very-welcoming-its-time-for-that-to-change/?cb=1), here is a very general answer, but that might lead you on the correct way to fix it yourself.
Type Mismatch is an error you can get when using a variable the wrong way. For example if you try to do numerical functions with Strings (which means the variable contains letters a-z etc) you will get "Type Mismatch" as you cant add or subtract text in a mathematical way... On the other hand you cant add Integer variables (the variable only contains a number AND isnt contained within "quote marks").
So below is a few ways to assigna a variable and what type it becomes:
LastID=1 'This makes LastID an INT (number)
LastID="1" 'This makes LastID a String but a CInt(LastID) can turn it into an INT because it ONLY contains numbers.
LastID="IT" 'This makes LastID a String that CANT in any way be cast to INT as it contains letters.
LastID=IT 'This row will either create an error except if you already have a variable called IT, then LastID will get the same value as the IT variable...
This should hopefully get you on your way to fix this issue...

Remove duplicate values from a string in classic asp

I have below code in classic asp
str=Request.Form("txt_str")
"txt_str" is text box in a classic asp form page where I am entering below values:
000-00001
000-00001
000-00001
000-00002
response.write str
hence str will be 000-00001 000-00001 000-00001 000-00002
array = split(str,Chr(44))
if str <> "" then
x=empty
for i = 0 to ubound(array)
if array(i) <> "" then
array_2 = split(array(i),chr(13) & chr(10))
for j = 0 to ubound(array_2)
if array_2(j) <> "" then
if x=empty then
x= "'" & array_2(j) & "'"
else
x= x & ",'" & array_2(j) & "'"
end if
end if
next
end if
next
End if
response.write x
hence x will be returned as '000-00001','000-00001','000-00001','000-00002'
I want to remove duplicate values from x and display only it as:
x = '000-00001','000-00002'
How can i achieve this.Any help on this would be appreciated.
Thanks
To remove duplicates of string lists, the best option IMO is to use a Dictionary object. You can use this short function to do the task on a given string array:
Function getUniqueItems(arrItems)
Dim objDict, strItem
Set objDict = Server.CreateObject("Scripting.Dictionary")
For Each strItem in arrItems
objDict.Item(strItem) = 1
Next
getUniqueItems = objDict.Keys
End Function
A simple test:
' -- test output
Dim arrItems, strItem
arrItems = Array("a","b","b","c","c","c","d","e","e","e")
For Each strItem in getUniqueItems(arrItems)
Response.Write "<p>" & strItem & "</p>"
Next
This is a sample for your use case:
' -- sample for your use case
Dim strInput, x
strInput = Request.Form("txt_str")
x = "'" & join(getUniqueItems(split(str, Chr(44))), "','") & "'"
BTW, did you notice that Array and Str are VBScript Keywords, so you may run into issues with using such variable names. Therefore, I think it is common practice in VBScript to use prefixes for variable names.
If it's a ordered list, consider using a variable with last value:
lastval = ""
array = split(str,Chr(44))
if str <> "" then
x=empty
for i = 0 to ubound(array)
if array(i) <> "" then
array_2 = split(array(i),chr(13) & chr(10))
for j = 0 to ubound(array_2)
if array_2(j) <> "" then
if array_2(j) <> lastval then
lastval = array_2(j)
if x=empty then
x= "'" & array_2(j) & "'"
else
x= x & ",'" & array_2(j) & "'"
end if
end if
end if
next
end if
next
End if

Vbscript hard validation

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

Can you please tell me what this error means?

Can you please tell me why I am getting the following error?
VBScript runtime error: This array is fixed or temporarily locked: 'temp'
This is the code that is generating the error. I am unsure of how to resolve it.
I am just trying to unpack a file that is in DRY folder and move it to ACS folder.
Thank you very much
Set FSO = CreateObject("Scripting.FileSystemObject")
Set fldr = FSO.GetFolder("C:\Ebooks\DRY\")
For Each fil In fldr.Files
If LCase( Right( fil.Name, 4 ) ) = ".zip" Then
zipFilePath = fil.Path
temp = file.Name
temp = Left( temp, LEN(temp) - 4 ) ' remove the .zip
temp = Split( temp, "_" ) ' split base name away from month-day-year
temp = temp( UBOUND(temp) ) ' get just month-day-year
temp = Split( temp, "-" ) ' get month day and year separately
mn = CINT(temp(0)) ' get the month number
dirName = MonthName(mn,True) & temp(2) ' True means get 3 letter abbrev for month
Response.Write "Unpacking " & fil.Name & " to directory " & dirName & "<br/>" & vbNewLine
objZip.UnPack zipFilePath, "D:\ACS\" & dirName & "\"
End If
Next
This is caused by:
temp = temp(ubound(temp))
and can be fixed by:
temp = (temp(ubound(temp)))
While you can assign to/overwrite an array variable with arbitrary values:
>> a = Array(1)
>> b = Array(2)
>> a = b
>> b = 4711
>> WScript.Echo Join(a), b
>>
2 4711
you can't assign an array element to the variable holding the array itself:
>> a = a(0)
>>
Error Number: 10
Error Description: This array is fixed or temporarily locked
>> a = Array(Array(1), Array(2))
>> a = a(1)
>>
Error Number: 10
Error Description: This array is fixed or temporarily locked
So re/mis-using the temp variable is one cause of your problem. The difference between "fil" and "file" will bite you next.
After reading Alex K's answer, I realise that you can avoid that error 10. I think that the outer () are 'pass me per value' parentheses, that create a copy ov the original array before the then harmless assignment. But I still believe that using proper variable names and not re-using variables is a better way.

date format in VBS

I want to get a date in full format in my vbscript. For example, I put
DateParam = FormatDateTime(Date()-1, 2)
But it returns
3/8/2012
I need to function to return
03/08/2012 instead.
Does anyone knows how to fix this?
The FormatDateTime function is useless, because it depends on the user specific and global Regional Settings.
The best (most gain for least effort) solution - tapping into .NET - is flawed for dates; again because of the dependency on the Regional Settings.
If you want/need to roll your own function, start with something like fmtDate().
Dim g_oSB : Set g_oSB = CreateObject("System.Text.StringBuilder")
Function sprintf(sFmt, aData)
g_oSB.AppendFormat_4 sFmt, (aData)
sprintf = g_oSB.ToString()
g_oSB.Length = 0
End Function
Function fmtDate(dtX)
fmtDate = Join(Array( _
Right(100 + Month(dtX), 2) _
, Right(100 + Day(dtX), 2) _
, Year(dtX) _
), "/")
End Function
Dim dtYesterday : dtYesterday = Date() - 1
WScript.Echo "Yesterday:", dtYesterday, GetLocale()
WScript.Echo "sprintf (silly) =>", sprintf("{0:MM/dd/yyyy}", Array(dtYesterday))
WScript.Echo "sprintf (clumsy) =>", sprintf("{0:MM}/{0:dd}/{0:yyyy}", Array(dtYesterday))
WScript.Echo "fmtDate =>", fmtDate(dtYesterday)
output:
Yesterday: 08.03.2012 1033
sprintf (silly) => 03.08.2012
sprintf (clumsy) => 03/08/2012
fmtDate => 03/08/2012
On second thought:
Escaping the "/" helps to make sprintf() usable:
WScript.Echo "sprintf (silly me) =>", sprintf("{0:MM\/dd\/yyyy}", Array(dtYesterday))
output:
sprintf (silly me) => 03/08/2012
So don't bother with fmt* functions but use .NET formatting.
ThisDate = Date()
MyDate = Right("0" & CStr(Month(ThisDate)), 2) & "/" & _
Right("0" & CStr(Day(ThisDate)), 2) & "/" & CStr(Year(ThisDate))

Resources