我有一张excel文件(让我们说文件X)有2张。在第一张表中我显示图表。其次,我有图表的数据。为了从图表中获取数据,我需要处理这些数据,就像我们在SQL中那样处理Group by,order by。有没有什么办法可以使用oledb在同一个excel文件(文件X)中使用VBA代码从第二张纸上读取数据?
谢谢!
答案 0 :(得分: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