When declaring a variable to blank (before a loop for example), it is sometimes done as "" or Empty. Also, when checking the value, it is sometimes used with "(Not IsEmpty(variable))" and "variable <> Empty". Is it better to use one vs another and can it cause any issues using it the wrong way?
Ex1:
fileNameDate = Empty
fileNameDate = ""
Ex2:
If (Not IsEmpty(fileNameDate)) Then
If fileNameDate <> Empty Then
If fileNameDate <> "" Then
Thanks!
------------Update-------------
Note that my question is not asking for the difference between Null, Empty, and Nothing. I'm simply concentrating on the "Empty" part and whether it's the same things as writing "". For the most part, I have received similar results when interchanging the two, but I dont know if it's just the examples I used. For example, the following confused me some.
My code:
Dim x, y, z
'Option1 (Do not set x to anything)
'Option2
'x = Empty
'Option3
'x = ""
If x = "" Then
'Action1
End if
If x = Empty Then
'Action2
End if
If IsEmpty(x) Then
'Action3
End if
If I go with Option1 and just not define "x", all three actions will occur.
If I go with Option2 and set x = Empty, all three actions will also occur
But if I go with Option3 and set x = "", only Action1 and Action2 occurs.
Why?
Some considerations:
fileNameDate = Empty ' The same as just declaring Dim fileNameDate
IsEmpty(fileNameDate) ' = True
Is not the same as:
fileNameDate = ""
IsEmpty(fileNameDate) ' = False
I think the function IsEmpty()is misnamed, because it checks if the variable has been initialized, not if it's actually empty.
Related
I'm creating a chatbot using VB6 and the whole basis of this chatbot is that whenever a user writes a 'trigger word', such as "good", "amazing", etc., the chatbot will reply "that's great".
However, whenever I don't write the trigger word, only the msgbox which says "Word is in this" appears, and I don't know what I'm doing wrong. I've tried messing around with the >, <, = signs to no avail. Any help will be appreciated.
Private Sub conversation()
Dim imput As String 'where user types to chatbot
Dim arrWords As Variant, aWord As Variant
arrWords = Array("good", "great", "bad")
Dim wordFound As Boolean
wordFound = False
For Each aWord In arrWords
If InStr(imput, aWord) = 0 Then
wordFound = True And MsgBox "Word is in this"
ElseIf InStr(imput, aWord) > 0 Then
wordFound = False And MsgBox "Word is not in this"
End If
Next
End Sub
Other answers have already explained that your logic is backwards, which it is.
But also, I don't know whether you have accurately copied your code or not, but when I copy it into VB, I get — as I expected — syntax errors on the lines with MsgBox in them. I can "fix" this by adding parentheses to the MsgBox arguments, so: wordFound = True And MsgBox("Word is in this"), etc. But that isn't good code, for reasons I will explain, and I have a few other suggestions.
Consider these changes to your code:
Private Sub conversation(theInput As String)
Dim arrWords As String, aWord As String
arrWords = Array("good", "great", "bad")
Dim wordFound As Boolean
wordFound = False
For Each aWord In arrWords
If InStr(theInput, aWord) = 0 Then
wordFound = False
MsgBox """" & aWord & """ is in this"
Else
wordFound = True
MsgBox """" & aWord & """ is not in this"
End If
Next
End Sub
Private Sub SendButton_Click()
conversation(myChatTextBox.Text)
End Sub
Ok. Here are some points.
Don't use Variant unless you have a compelling reason to do so. It's the least efficient way to store information, because it has to allocate extra memory to tell internally what type of variable it is, and it also has to allocate enough memory to contain the largest possible type it could be. (A String variable has 10 bytes plus one per character in the string, while a Variant type allocated as a string has 22 bytes plus one per character in the string.)
I changed imput to theInput. input is a reserved word in VB, so you can't use it, but it's clearer to other people if you don't misspell the word. Better to find some prefix to put on it.
As others have said, when InStr returns zero, that means that the string in argument 2 isn't in the string in argument 1. So, it means that the "word isn't in this," not that it is. (That's the answer to the trouble you're having; the rest of this is just to improve your code overall.)
wordFound = True And MsgBox("Word is in this") only works by coincidence. MsgBox returns a value of 1 when it runs successfully without arguments. (Who knew? I had to try it out for myself. Probably because it can be set up to return a number of different values for different types of ms) So your logic is wordFound = True And 1. And is a logical comparison operator: True And 1 evaluates to True, while False And 1 evaluates to False. So, you get what you want, but pretty much by accident. Put the two code bits on two different lines. You don't need to logically compare them; in fact it doesn't make sense to do so. (If you want to actually put two lines of code on the same line, put a colon between them: wordFound = True : MsgBox "etc", but this isn't generally considered good practice as the code is less readable. I have the feeling you thought you were using And to do this, and as you can see it does something quite different.)
I changed your message to include the word you're looking for in quotes, for example "good" is in this. To get a literal quotation mark in a string, use two of them: "". (You have to put the two quotes in quotes themselves, since they are a quoted string; that's why there are four of them at the beginning and three later on.)
You don't need an ElseIf here, because if your If condition is false, your ElseIf condition is true. You only need ElseIf if you are evaluating more than two possible conditions.
I've set up the basic idea of how to send the chatbox user's input to your conversation subroutine. When the user clicks a Send button, you send the contents of the text box to conversation as the input argument. If you set it up as a local variable, you have to write some sort of code to grab the user's input. This is the cleaner way to do the job.
All that said, you can further simplify your For Each loop like this:
For Each aWord In arrWords
wordFound = InStr(input, aWord) > 0
MsgBox """" & aWord & """ is" & IIf(wordFound, "", " not") & " in this"
Next
Explanations:
InStr(input, aWord) <> 0 is either true or false. You assign whichever it is to wordFound. This is a more concise way of doing your If...Else. (A simpler example of the idea: x = 1 = 1 will set x equal to True, while x = 1 = 0 will set x equal to false. You can use parentheses to make it easier to understand: x = (1 = 1), etc.)
IIf ("instant if") takes the form of IIf(condition, valueIfConditionIsTrue, valueIfConditionIsFalse).
Since wordFound is a boolean value, saying wordFound is the same as saying wordFound = True, so you can omit the = True (you can also say Not wordFound to mean the same thing as wordFound = False).
EDIT: If you want your chatbot to reply "that's great" when any one of the words is encountered, change conversation() from a Sub to a Function and return true or false. Like this:
Private Function conversation(theInput As String) As Boolean
Dim arrWords As String, aWord As String
arrWords = Array("good", "great", "bad")
'Get rid of your wordFound variable — you don't need it any more
conversation = False
For Each aWord In arrWords
If InStr(theInput, aWord) > 0 Then
conversation = True
End If
Next
End Function
Private Sub SendButton_Click()
If conversation(myChatTextBox.Text)
MsgBox "That's great!"
Else
MsgBox "That's not so great."
End If
End Sub
Jim Mack's answer is correct; I would make the comparison more robust by adding (before the for loop):
imput = UCase(imput)
and making the array of test words all uppercase. Fundamentally, there was just a logic problem with the original code (probably due to a misunderstanding of the language).
The ElseIf clause is somewhat worrisome, too; in general, it's wise to include an explicit else clause to handle any test that falls through all the previous conditions.
I didn't try to run your code -- it doesn't even look like it would run -- but at least one error jumps out.
If InStr(imput, aWord) = 0 Then
wordFound = True And MsgBox "Word is in this"'
...doesn't do what you seem to think it does. You're saying that wordFound will be true when the word is NOT in the input (InStr = 0), but only when the MsgBox returns a non-zero result
What you want is something like:
If InStr(imput, aWord) > 0 Then ' >0 means word was found
wordFound = True
MsgBox "Word is in this"'
The parallel is true for the 'not found' condition.
I have a return value from the database but I can not filter the null value.
With rs_receita
Do Until .EOF
Set noaux2 = xml.createElement("Superavit")
noaux2.Text = IIf(IsEmpty(!Superavit), "", CStr(!Superavit))
Call noaux.appendChild(noaux2)
.MoveNext
Loop
End With
Set rs_receita = Nothing
Avoid IIf for this scenario. IIf always evaluates both expressions. So when !Superavit is null, this will cause an error.
A single-line If statement, on the other hand, will only evaluate the expression to be executed. Combine that with the IsNull() function to reliably assign a database value to a variable if it's not null:
If IsNull(!Superavit) Then noaux2.Text = "" Else noaux2.Text = CStr(!Superavit)
In VB6 (I'm sorry!) you can force coercion to a string by appending an empty string to the field value.
Edit: Phew, this article is a blast from the past. It gives a bunch of NULL handling ideas for classic VB6: https://technet.microsoft.com/en-us/library/Aa175775(v=SQL.80).aspx
I believe either of the following will work:
noaux2.Text = "" & rs("Superavit")
OR
noaux2.Text = vbNullString & rs("Superavit")
I ran into an issue with the Classic ASP VbScript InStr() function. As shown below, the second call to InStr() returns 1 when searching for an empty string in a non empty string. I'm curious why this is happening.
' InStr Test
Dim someText : someText = "So say we all"
Dim emptyString : emptyString = ""
'' I expect this to be true
If inStr(1,someText,"so",1) > 0 Then
Response.write ( "I found ""so""<br />" )
End If
'' I expect this to be false
If inStr(1, someText, emptyString, 1) > 0 Then
Response.Write( "I found an empty string<br />" )
End If
EDIT:
Some additional clarification: The reason for the question came up when debugging legacy code and running into a situation like this:
Function Go(value)
If InStr(1, "Option1|Option2|Option3", value, 1) > 0 Then
' Do some stuff
End If
End Function
In some cases function Go() can get called with an empty string. The original developer's intent was not to check whether value was empty, but rather, whether or not value was equal to one of the piped delimited values (Option1,Option2, etc.).
Thinking about this further it makes sense that every string is created from an empty string, and I can understand why a programming language would assume a string with all characters removed still contains the empty string.
What doesn't make sense to me is why programming languages are implementing this. Consider these 2 statements:
InStr("so say we all", "s") '' evaluates to 1
InStr("so say we all", "") '' evaluates to 1
The InStr() function will return the position of the first occurrence of one string within another. In both of the above cases, the result is 1. However, position 1 always contains the character "s", not an empty string. Furthermore, using another string function like Len() or LenB() on an empty string alone will result in 0, indicating a character length of 0.
It seems that there is some inconsistency here. The empty string contained in all strings is not actually a character, but the InStr() function is treating it as one when other string functions are not. I find this to be un-intuitive and un-necessary.
The Empty String is the Identity Element for Strings:
The identity element I (also denoted E, e, or 1) of a group or related
mathematical structure S is the unique element such that Ia=aI=a for
every element a in S. The symbol "E" derives from the German word for
unity, "Einheit." An identity element is also called a unit element.
If you add 0 to a number n the result is n; if you add/concatenate "" to a string s the result is s:
>> WScript.Echo CStr(1 = 1 + 0)
>> WScript.Echo CStr("a" = "a" & "")
>>
True
True
So every String and SubString contains at least one "":
>> s = "abc"
>> For p = 1 To Len(s)
>> WScript.Echo InStr(p, s, "")
>> Next
>>
1
2
3
and Instr() reports that faithfully. The docs even state:
InStr([start, ]string1, string2[, compare])
...
The InStr function returns the following values:
...
string2 is zero-length start
WRT your
However, position 1 always contains the character "s", not an empty
string.
==>
Position 1 always contains the character "s", and therefore an empty
string too.
I'm puzzled why you think this behavior is incorrect. To the extent that asking Does 'abc' contain ''? even makes sense, the answer has to be "yes": All strings contain the empty string as a trivial case. So the answer to your "why is this happening" question is because it's the only sane thing to do.
It is s correct imho. At least it is what I expect that empty string is part of any other string. But maybe this is a philosophical question. ASP does it so, so live with it. Practically speaking, if you need a different behavior write your own Method, InStrNotEmpty or something, which returns false on empty search string.
I have 6400+ records which I am looping through. For each of these: I check that the address is valid by testing it against something similar to what the Post Office uses (find address). I need to double check that the postcode I have pulled back matches.
The only problem is that the postcode may have been inputted in a number of different formats for example:
OP6 6YH
OP66YH
OP6 6YH.
If Replace(strPostcode," ","") = Replace(xmlAddress.selectSingleNode("//postcode").text," ","") Then
I want to remove all spaces from the string. If I do the Replace above, it removes the space for the first example but leave one for the third.
I know that I can remove these using a loop statement, but believe this will make the script run really slow as it will have to loop through 6400+ records to remove the spaces.
Is there another way?
I didn't realise you had to add -1 to remove all spaces
Replace(strPostcode," ","",1,-1)
Personally I've just done a loop like this:
Dim sLast
Do
sLast = strPostcode
strPostcode = Replace(strPostcode, " ", "")
If sLast = strPostcode Then Exit Do
Loop
However you may want to use a regular expression replace instead:
Dim re : Set re = New RegExp
re.Global = True
re.Pattern = " +" ' Match one or more spaces
WScript.Echo re.Replace("OP6 6YH.", "")
WScript.Echo re.Replace("OP6 6YH.", "")
WScript.Echo re.Replace("O P 6 6 Y H.", "")
Set re = Nothing
The output of the latter is:
D:\Development>cscript replace.vbs
OP66YH.
OP66YH.
OP66YH.
D:\Development>
This is the syntax Replace(expression, find, replacewith[, start[, count[, compare]]])
it will default to -1 for count and 1 for start. May be some dll is corrupt changing the defaults of Replace function.
String.Join("", YourString.Split({" "}, StringSplitOptions.RemoveEmptyEntries))
Because you get all strings without spaces and you join them with separator "".
I have the following VBScript in a reusable action:
'Gather links
Browser("1").Navigate "http://InternalWebmail/something/inbox.nsf"
set oDesc = Description.Create()
oDesc("micclass").Value = "Link"
set links = Browser("1").Page("Webmail").ChildObjects(oDesc)
Dim links2
links2 = ""
'Filter out irrelevant links
For i = 0 To links.Count-1
If lcase(trim(links(i).GetROProperty("text"))) = lcase(trim(DataTable("ExpectedFrom", dtGlobalSheet))) Then
links2 = links2 + "," + links(i).GetROProperty("url")
End If
Next
Dim final
final = split(mid(links2,2),",") 'Remove leading comma and split into array
'For each link (i.e. for each E-mail received):
'Effectively giving a reusable action an input parameter, I hope
For i = 0 To final.Count - 1 'error: Object Required
DataTable("url","CheckHeader") = final(i)
RunAction "CheckHeader", oneIteration
Next
Everything runs just fine, until I get to the declaration of the loop at the bottom of the snippet. There, QTP gives me an error "Object Required" and refuses to elaborate.
i has a leading value of 58, though I've tried setting it to 0 prior to entering the loop.
final is an array of 6 strings, each a URL. All have a value.
If I msgbox(final(2)), I see the value of final(2) as being valid.
isobject(final(1)) = false
final(1) has the correct value
msgbox(final is nothing) and msgbox(final(1) is nothing) yield the same error.
It looks as if the array is null but somehow the array has members?
How is this possible?
What is QTP talking about?
In vbscript arrays don't have a Count property, you should use UBound
x = split("how now brown cow")
' MsgBox x.Count ' error
MsgBox UBound(x) ' 3
The reason .Count worked for the first loop is that ChildObjects does not return an array, it returns a COM collection object. That is also why you had to use the Set statement when assigning to links but not when assigning to final.