2017-10-28 101 views
1

此代碼是用Excel2010 VBA內部組件和查詢,PostgreSQL表變量未IN子句

我在VBA下面的代碼創建,我想在我的SQL查詢中使用一個變量,但我不能讓使用IN子句接受VBA變量的SQL查詢

此代碼創建我想要使用的變量並且正常工作。這使我可以選擇特定的細胞,我需要查詢SelectedID = 6,7,8,6452

我現在想要將它添加到使用IN子句我的查詢,但它的

Dim StaffID As Range 
Dim ID As Range 
Dim LR As Long 
Dim SelectedID As String 

'Count number of rows to search 
LR = Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row 
On Error Resume Next 'if only 1 row 

'Store Data from here 
Set StaffID = ThisWorkbook.Sheets("Sheet1").Range("B2:B" & LR) 

'Loop through each cell in Range and look for any character in column A 
'then store offset cell value using comma delimiter 
For Each ID In Worksheets("Sheet1").Range("A2:A" & LR).Cells 
    If ID.Value > 0 Then 
     SelectedID = SelectedID & "," & ID.Offset(, 1).Value 
    End If 
Next ID 

'Remove first delimiter from string (,) 
SelectedID = Right(SelectedID, Len(SelectedID) - 1) 

輸出例只是不起作用。有沒有人有解決方案或解決方法。

Sheets("Sheet2").Select 
Range("A1").Select 
Dim rs As Recordset 

Dim t As String 
t = "SELECT DISTINCT s.entity_id, u.login_name, s.role " _ 
      & "FROM staff s INNER JOIN user u ON s.entity_id=u.staff_id " _ 
      & "WHERE u.staff_id IN (SelectedID) " _ 

Set rs = conn.Execute(t) 
With ActiveSheet.QueryTables.Add(Connection:=rs, Destination:=Range("A1")) 
    .Refresh 
End With 

rs.Close 

回答

2

此時您將字符串'SelectedID'直接放入查詢中。你需要像這樣在您的VBA:

t = "SELECT DISTINCT s.entity_id, u.login_name, s.role " _ 
      & "FROM staff s INNER JOIN user u ON s.entity_id=u.staff_id " _ 
      & "WHERE u.staff_id IN (" & SelectedID & ")" 
+0

謝謝。那就是訣竅。 – BradleyS

0

Rows.Count應該是完全合格的With ThisWorkbook.Worksheets("Sheet1")充分排位賽將讓你的代碼讀取更好。

Function getSelectedIDSQL() As String 
    Dim ID As Range, StaffID As Range 
    Dim SelectedID As String 

    With ThisWorkbook.Worksheets("Sheet1") 
     For Each ID In .Range("A2" & .Range("A" & .Rows.Count).End(xlUp)) 
      If ID.Value > 0 Then SelectedID = SelectedID & "," & ID.Offset(, 1).Value 
     Next 
    End With 

    If Len(SelectedID) Then getSelectedIDSQL = Right(SelectedID, Len(SelectedID) - 1) 

End Function