1

我需要使用 VBA 使用 sql 查询。我的查询输入值来自 excel 表中的列。我需要获取列中存在的所有值,它应该作为查询的输入传递给 sqlserver。但我无法得到答案。我将类型不匹配视为错误。任何人都可以帮助我。提前致谢

例如在 J 列中包含 J1=25, j2=26, ....so on

stSQL = "SELECT * FROM prod..status where state in"      

stSQL = stSQL & wsSheet.Range("J:J").Value

我的完整代码如下

Sub Add_Results_Of_ADO_Recordset()

     'This was set up using Microsoft ActiveX Data Components version 2.8

    Dim cnt As ADODB.Connection
    Dim rst As ADODB.Recordset
    Dim stSQL As Variant
    Dim wbBook As Workbook
    Dim wsSheet As Worksheet
    Dim rnStart As Range


    Const stADO As String = "Provider=SQLOLEDB.1;Integrated Security=SSPI;" & _
    "Persist Security Info=False;" & _
    "Initial Catalog=prod;" & _
    "Data Source=777777777V009D\YTR_MAIN4_T"
     'where BI is SQL Database & AURDWDEV01 is SQL Server

    Set wbBook = ActiveWorkbook
    Set wsSheet = wbBook.Worksheets("sheet1")

    With wsSheet
        Set rnStart = .Range("A2")
    End With


     ' My SQL Query       



    stSQL = "SELECT  * FROM prod..status where state in"



stSQL = stSQL + wsSheet.Range("J:J").Value


    Set cnt = New ADODB.Connection

    With cnt
        .CursorLocation = adUseClient
        .Open stADO
        .CommandTimeout = 0
        Set rst = .Execute(stSQL)
    End With

     'Here we add the Recordset to the sheet from A1
    rnStart.CopyFromRecordset rst

     'Cleaning up.
    rst.Close
    cnt.Close
    Set rst = Nothing
    Set cnt = Nothing

End Sub
4

3 回答 3

0

我使用 for 循环和 mid 命令将列中的值转换为单个变量。下面是我用来执行我需要的功能的代码

' Getting the last row
With wsSheet
lastrow1 = .Range("J" & .Rows.Count).End(xlUp).Row
End With

' Appending the values to a single variable

For i = 1 To lastrow
  s1 = s1 & "'" & Val(wsSheet.Cells(i, 10)) & "'" & ","
Next



' Variable which could be used in  IN command    

    If lastrow > 0 Then
        s1 = Mid(s1, 1, Len(s1) - 1)
        s1 = "(" & s1 & ")"
    Else
         Exit Sub
    End If
于 2013-11-06T09:59:35.433 回答
0

stSQL 变量中的“in”之后没有空格。因此,如果您的单元格包含值“TEST”,stSQL 将是

SELECT * FROM prod..status where state inTEST
于 2013-11-05T11:42:33.707 回答
0

改成

stSQL = stSQL + " ('" + Replace(wsSheet.range("J:J").Value, "'", "") + ")"

但是sql IN语句通常是这样使用的

state IN (25,26,28)

但是,如果您只使用一个整数值,您可能希望采用这种方式。

stSQL = "SELECT * FROM prod..status where state = "
stSQL = Val(wsSheet.range("J:J").Value)

使用 in 语句虽然有一件事是危险的。如果你的 In 部分语句很长,它会变得很慢,然后随着更大的 in 语句完全崩溃。

这种情况的解决方案是创建一个带有 in 值的临时表,并在(临时表)中执行位置或基于临时表的内部连接

于 2013-11-05T11:58:12.577 回答