Excel VBA SQL查询,其变量值可能为空

时间:2016-05-26 13:53:47

标签: sql excel vba

我正在尝试使用SQL查询在Excel中工作。 在工作表中,我有一个包含5个数字的列表(单元格中有一个)。我有查询工作,如果所有5个单元格中都有一个数字,它工作正常。但是,如果单元格为空,我还需要它才能运行。例如只有3个单元格,数字在。

有没有办法做到这一点?

我的代码是例如:

var1 = worksheets("Sheet1").Range("A1")
var2 = worksheets("Sheet1").Range("A2")
var3 = worksheets("Sheet1").Range("A3")
var4 = worksheets("Sheet1").Range("A4")

Select * from Schema.Table WHERE column1 = " & var1 & " AND (column1 = " & var2 & " etc....

任何编码方式,如果var3为空,它将从SQL查询中排除吗?

由于

3 个答案:

答案 0 :(得分:0)

是的,很容易:

Dim szSQL As String

szSQL = "select * from Schema.Table WHERE "
If (var1 <> "") Then szSQL = szSQL & "column1 = " & var1
If (var1 <> "" And var2 <> "") Then szSQL = szSQL & " AND "
If (var2 <> "") Then szSQL & " column2 = " & var2

答案 1 :(得分:0)

counter = 0
sqltext = 'Select * from Schema.Table '

if var1 <> '' then
   counter = counter + 1
   if counter > 1 then
     sqltext = sqltext & ' and column1 = ' & var1
   else
     sqltext = sqltext & ' where column1 = ' & var1
   end if
end if
if var2 <> '' then
   counter = counter + 1
   if counter > 1 then
     sqltext = sqltext & ' and column2 = ' & var2
   else
     sqltext = sqltext & ' where column2 = ' & var2
   end if
end if

等。

答案 2 :(得分:0)

我会在数组中构建所有条件,并使用Join格式化最终查询:

Sub BuildQuery()
  Dim headers(), values(), conditions(), value, i&, ii&

  ' load the headers and values in an array '
  headers = VBA.Array("column1", "column2", "column3", "column4", "column5")
  values = ActiveSheet.Range("A1:A5").value

  ' create each condition for each non empty value '
  ReDim conditions(0 To UBound(headers))
  For Each value In values
    If Len(value) Then
      conditions(ii) = headers(i) & " = " & value
      ii = ii + 1
    End If
    i = i + 1
  Next
  ReDim Preserve conditions(0 To ii - 1)

  ' build the final query '
  Debug.Print "Select * from Schema.Table WHERE " & Join(conditions, " And ")
End Sub