我正在尝试编写一些可以使用SQL在VBA中查询命名范围的VBA。目前,它工作得相当好,但我有一个问题,每次我运行宏时,都会打开工作表的只读实例。我想使用宏来查询同一工作簿中的范围,而无需打开只读副本。
这是我的代码
Public Sub QueryAndOutputToCell(ByVal query As String, rng As Range)
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Dim DBFullName, connString, SQL As String
DBFullName = ThisWorkbook.path & "\" & ThisWorkbook.name
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & DBFullName & "';Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';"
conn.connectionString = connString
conn.Open ' Read-only copy is opened here
conn.commandtimeout = 0
Dim cubeData As ADODB.Recordset
Set cubeData = New ADODB.Recordset
cubeData.Open query, conn, adOpenDynamic, adLockReadOnly
rng.CopyFromRecordset cubeData
cubeData.Close
conn.Close
Set cubeData = Nothing
Set conn = Nothing
End Sub
有人知道这是否可行?