1

我有一个带有 2 张纸的 excel 文件(让我们说文件 X)。在第一张表中,我显示图表。其次,我有图表的数据。为了从图表中获取数据,我需要像在 SQL 中那样处理这些数据,例如 Group by、order by。有什么方法可以使用 oledb 在同一个 excel 文件(文件 X)中使用 VBA 代码从第二张表中读取数据?

谢谢!!

4

1 回答 1

3

这是一个使用 SQL 连接来自两个范围的数据的示例:如果文件处于打开状态,它将正常工作(只要它已保存,因为您需要文件路径)。

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-25T18:10:23.183 回答