Link to home
Start Free TrialLog in
Avatar of kerrybenno
kerrybenno

asked on

SQL retrieving records where a field isNull

In Excel I am retrieving data in vba using sql.

I have the following code;


Function SummarySQL()

Dim FirstDate As Date
Dim Sector As String
Dim Team As String
Dim TabCode As String

FirstDate = Range("FirstDate").Value
Sector = Range("Sector").Value
Team = Range("Team").Value
TabCode = "Additional Resources"

If Sector = "Show All" Then
    Sector = "%"
End If

If Team = "Show All" Then
    Team = "%"
End If

SummarySQL = "SELECT * FROM [" & DataRange & "] WHERE [Month Year] = " & CDbl(FirstDate) & " " & _
             "AND [Sector] Like '" & Sector & "'" & " " & _
             "AND [TabCode] Like '" & TabCode & "'" & " " & _
             "AND [Team] Like '" & Team & "'" & ";"

End Function


Sometimes the Sector field will have been left empty, so where it's returning all with %, I also need it to return the nulls too.  When Sector <> % I don't want the nulls.

i hope this makes sense.

Thanks in advance.
ASKER CERTIFIED SOLUTION
Avatar of cmhunty
cmhunty

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Shanmuga Sundaram D
Try replacing as this

If Sector = "Show All" Then
    Sector = "% "  and " Sector is not null "
End If
Sorry I am wrong in previous. Try replacing as this
If Sector = "Show All" Then
    Sector =  " [Sector] Like  % "
End If

If Team = "Show All" Then
    Team = "%"
End If

If Sector <> " [Sector] Like  %'"  Then
    Sector = " Sector is not null "
End If


SummarySQL = "SELECT * FROM [" & DataRange & "] WHERE [Month Year] = " & CDbl(FirstDate) & " " & _
             "AND "  & Sector & "  & _
             "AND [TabCode] Like '" & TabCode & "'" & " " & _
             "AND [Team] Like '" & Team & "'" & ";"