2

我看到一个大约一年前更新的问题,让我在找到我需要的解决方案方面走了很长一段路,但导致的问题多于答案。

首先让我说我不是 SQL(DB2、SQLServer、Oracle)的“新手”,但我是在 Excel 中使用 SQL 的相对“新手”。此外,我在 2010 年工作,但必须保持与 2003 年的兼容性。

我要做的是将一张表中的数据与另一张表匹配并报告异常。我想从“Open Lines”中挑选 6 列,并将它们与“Back Orders”中的 3 列相匹配,并且只显示例外情况。'Open Lines' 可以是 1..n,而 'Back Orders' 可以是 0..n。我只想抓住存在“延期交货”的行。

要编写普通的 SQL,我会这样做:

SELECT 
O.[Part Number], O.[Part Desc], O.[Source Domain], O.[Ship Qty], O.[Date Created],
B.[Dest Domain], B.[Quantity], B.[Date Created] 
FROM [OPEN LINES] O
JOIN [Back Orders] B ON O.[Part Number] = B.[Part Number]
WHERE B.[Part Number] IS NOT NULL
ORDER BY O.[Part Number] 

问题是我无法在没有错误的情况下通过连接。这就是我到目前为止所拥有的。

rs.Open "SELECT [OPEN LINES$].[Part Number], [OPEN LINES$].[Part Desc], " $ _
"[OPEN LINES$]. [Source Domain], " & _
"[OPEN LINES$].[Ship Qty], [OPEN LINES$].[Date Created] " & _
"FROM [OPEN LINES$] " & _
"JOIN [Back Orders$] ON [OPEN LINES$].[Part Number] = [Back Orders$].[Part Number] " & _
"ORDER BY [OPEN LINES$].[Part Number] ;", cn

如果您能提供任何帮助,我将不胜感激。

戈德

4

1 回答 1

3

尝试这个:

rs.Open "SELECT [OPEN LINES$].[Part Number], [OPEN LINES$].[Part Desc], " $ _
    " [OPEN LINES$]. [Source Domain], " & _
    " [OPEN LINES$].[Ship Qty], [OPEN LINES$].[Date Created] " & _
    " FROM [OPEN LINES$], [Back Orders$] " & _
    " WHERE [OPEN LINES$].[Part Number] = [Back Orders$].[Part Number] " & _
    " ORDER BY [OPEN LINES$].[Part Number]", cn

您不需要结束分号。

这是一个更简单的示例(在 XL2010 中测试)

Sub SqlJoin()

    Dim oConn As New ADODB.Connection
    Dim oRS As New ADODB.Recordset
    Dim sPath
    Dim sSQL As String

    sSQL = "select a.blah from <t1> a, <t2> b where a.blah = b.blah"

    sSQL = Replace(sSQL, "<t1>", Rangename(Sheet1.Range("A1:A5")))
    sSQL = Replace(sSQL, "<t2>", Rangename(Sheet1.Range("C1:C3")))

    If ActiveWorkbook.Path <> "" Then
      sPath = ActiveWorkbook.FullName
    Else
      MsgBox "Workbook being queried must be saved first..."
      Exit Sub
    End If

    oConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & sPath & "';" & _
                 "Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"

    oRS.Open sSQL, oConn

    If Not oRS.EOF Then
        Sheet1.Range("E1").CopyFromRecordset oRS
    Else
        MsgBox "No records found"
    End If

    oRS.Close
    oConn.Close

End Sub

Function Rangename(r As Range) As String
    Rangename = "[" & r.Parent.Name & "$" & _
                r.Address(False, False) & "]"
End Function
于 2013-03-08T23:48:48.087 回答