How I can treat null value in vb6 ResultSet - vb6

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")

Related

Using Array with Instr

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.

Using Empty vs "" to define or test a variable in VBscript

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.

IsNull in sybase where clause

I am using vb6 front end and sybase as backend. Can I use IsNull in where clause OR I must use = NULL
SQLStr = "select distinct thrd_pty.id_thrd_pty, thrd_pty.name_thrd_pty, thrd_pty.nbr_tax_idtn " _
& "from thrd_pty, cntct_rltn, cntct " _
& "where cntct.id_cntct = '" & cntct(ColNum, CurThrdPty) & "' and cntct_rltn.id_super = cntct.id_cntct and cntct_rltn.name_super = 'cntct' and thrd_pty.id_thrd_pty = cntct_rltn.id_thrd_pty and cntct_rltn.dt_eff_end IsNull "
The usual syntax in Sybase is either AND cntct_rltn.dt_eff_end IS NULL (which is perfectly fine for your example) or ISNULL(cntct_rltn.dt_eff_end, 0) for the more complicated stuff where you want to replace null with a defined default value. But you can do any of the follownig in ASE 15:
Adaptive Server treats null values in different ways, depending on the operators that you use and the type of values you are comparing. In general, the result of comparing null values is UNKNOWN, since it is impossible to determine whether NULL is equal (or not equal) to a given value or to another NULL. The following cases return TRUE when expression is any column, variable or literal, or combination of these, which evaluates as NULL:
expression is null
expression = null
expression = #x where #x is a variable or parameter containing NULL. This exception facilitates writing stored procedures with null default parameters.
expression != n where n is a literal not containing NULL and expression evaluates to NULL. (source)
(uppercase is mine as a personal style preference)
As a side note, you can also use COALESCE() function to deal with NULL values, but in your use case it won't add anything useful.
Reference:
Testing column for NULL values at Sybase infocenter
ISNULL as a function
COALESCE
Use is null:
cntct_rltn.dt_eff_end is null
More info, here
EDIT:
cQ = "update var1 = null ".(can be) .cQ = "update var1 is null" ?????
– niru dyogi
If you are updating, you have to use the assignment operator =. You can use is null only when evaluating conditions (such as the one in the example you provided).

How to Find Record Set Value is Number or String?

Original:
Using VB6
If rsCardEvent(4).Value = Str Then
TimOut = rsCardEvent(4)
Else
TimeOut = Left(TimOut, 2) & ":" & Mid(TimOut, 3, 2) & ":" & Right(TimOut, 2)
End If
Getting Type MisMatch Error.
How To Find Record Set Value is String or Number
Exactly i need
If Number means print number like Time Format (HH:MM:SS)
else
print string value
Coding Help for the above condition
Edited Version:
I'm working with an ADO.Recordset object and am trying to determine the data type of a column at run-time. I need to handle the column value differently in my code depending on its underlying data type. If the column value is a string, I want to work with the value as-is. If it is a number, I want to treat the number as an packed time and convert it to HH:MM:SS format (i.e. the number 120537 would be converted to the string "12:05:37").
Below is some example code that demonstrates what I want to achieve. However, when I run this code I get a "Type Mismatch" error:
If rsCardEvent(4).Value = Str Then
TimOut = rsCardEvent(4)
Else
TimeOut = Left(TimOut, 2) & ":" & Mid(TimOut, 3, 2) & ":" & Right(TimOut, 2)
End If
Have a look at the Visual Basic 6 function library. There are functions that can help you determine the underlying type of a value.
There are quite a few but you might find these useful:
IsNumeric
IsDate
Based on this article, if rsCardEvent is an ADO recordset, you could check the Type property. Something like this:
Select Case rsCardEvent(4).Type
Case adBSTR, adChar, adVarChar, adWChar, _
adVarWChar, adLongVarChar, adLongVarWChar
' It is a string '
Case Else
' It is not a string '
End Select
You can use the IsNumeric function available in VB6.
How about:
If TypeName(rsCardEvent(4).Value) = "String" then
http://msdn.microsoft.com/en-us/library/5422sfdf.aspx

QTP: Object Required errors when Object is valid

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.

Resources