好的,所以我有这个函数,它使用我传递给它的查询字符串来查询数据库。目前它在工作表中输出查询结果。如何获得函数以将结果作为可在 VBA 中用于执行计算等的范围?然后我将如何引用这个范围?例如,在结果中获取“名称”列。
Function Access_Data(query As String)
'Requires reference to Microsoft ActiveX Data Objects xx Library
Dim Cn As ADODB.Connection, Rs As ADODB.Recordset
Dim MyConn, sSQL As String
Dim Rw As Long, Col As Long, c As Long
Dim MyField, Location As Range
'Set destination
Set Location = Sheets(1).Range("a1")
'Set source
MyConn = "S:\Docs\Harry\Engine Client\Engine3.accdb"
'Create query
sSQL = query
'Create RecordSet
Set Cn = New ADODB.Connection
With Cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn
Set Rs = .Execute(sSQL)
End With
'Write RecordSet to results area
Rw = Location.Row
Col = Location.Column
c = Col
Do Until Rs.EOF
For Each MyField In Rs.Fields
Cells(Rw, c) = MyField
c = c + 1
Next MyField
Rs.MoveNext
Rw = Rw + 1
c = Col
Loop
Set Location = Nothing
Set Cn = Nothing
结束功能