我使用以下代码从SAME Excel工作表的Sheet1中读取数据。我将数据加载到返回数组中。 Excel工作表文件具有"只读"检查并始终打开" READ ONLY"模式。
问题,如果我更改了Sheet1上的任何数据,因为该文件以"只读"打开,它不会反映在ADO查询。 ADO继续输出"保存的#34;文件并忽略临时只读版本中已更新的内容。 例如,下面的值为" Col5:6"来自细胞" E6"。如果我将值替换为" test",ADO仍会输出" Col5:6"
如何让ADO读取Sheet1上的当前数据而不必"另存为"?
Sub sbADO()
Dim sSQLSting As String
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath As String, sconnect As String
Dim returnArray
DBPath = ThisWorkbook.FullName
sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPath _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Conn.Open sconnect
sSQLSting = "SELECT * From [Sheet1$] "
mrs.Open sSQLSting, Conn
returnArray = mrs.GetRows
mrs.Close
Conn.Close
Debug.Print returnArray(4, 4) '>> "Col5:6"
End Sub
答案 0 :(得分:1)
您无法使用ADO从Excel工作表中读取未保存的更改,因为未保存的数据位于内存(RAM,可能是交换文件)中,ADO旨在连接到DB 文件或服务器基于DB。
如果您认为SQL是唯一的方法,并且您的WHERE
子句非常简单,那么您可以使用内置功能的ADO Recordset进行过滤和排序,而无需进行连接。执行以下操作:
有一个代码示例:
Option Explicit
Sub FilterSortRecordset()
Dim arrHead
Dim strXML As String
Dim i As Long
Dim objXMLDoc As Object
Dim objRecordSet As Object
Dim arrRows
' get source in XML format
With Sheets("Sheet1")
arrHead = Application.Index(.Range("A1:G1").Value, 1, 0)
strXML = .Range("A2:G92").Value(xlRangeValueMSPersistXML)
End With
' fix field names
For i = 1 To UBound(arrHead)
strXML = Replace(strXML, "rs:name=""Field" & i & """", "rs:name=""" & arrHead(i) & """", 1)
Next
' load source XML into XML DOM Document
Set objXMLDoc = CreateObject("MSXML2.DOMDocument")
objXMLDoc.LoadXML strXML
' convert the document to recordset
Set objRecordSet = CreateObject("ADODB.Recordset")
objRecordSet.Open objXMLDoc
' filtering and sorting
objRecordSet.Filter = "City='London' OR City='Paris'"
objRecordSet.Sort = "ContactName ASC"
' populate another sheet with resulting recordset
arrRows = Application.Transpose(objRecordSet.GetRows)
With Sheets("Sheet2")
.Cells.Delete
.Cells.NumberFormat = "@"
For i = 1 To objRecordSet.Fields.Count
.Cells(1, i).Value = objRecordSet.Fields(i - 1).Name
Next
.Cells(2, 1).Resize(UBound(arrRows, 1), UBound(arrRows, 2)).Value = arrRows
.Columns.AutoFit
End With
End Sub
Sheet1
的资料数据如下:
然后我在Sheet2
上得到了结果: