【发布时间】:2020-09-12 17:48:34
【问题描述】:
对我来说,ADODB 是我渴望学习的新事物。这是我尽力而为但需要您的想法以使其看起来更专业和更高效的代码。代码中的问题是数据是以相反的顺序从工作表中获取的,而不是按工作表的顺序。为了清楚起见,我有Sample.xlsx 工作簿与两张表Sheet1 和New 并且代码应该循环通过这些表然后搜索特定标题然后从这样的列中获取数据。所有这一切都与 ADO 方法有关。代码首先从新工作表中获取数据,然后从 Sheet1 中获取数据。虽然工作表的顺序是 Sheet1,然后是 New >> 另一点,但如何正确关闭记录集。我的意思是使用 .Close 就足够了,否则我必须将其设置为 Nothing Set rs=Nothing。
Sub ImportFromClosedWorkbook()
Dim e, ws As Worksheet, cn As ADODB.Connection, rs As ADODB.Recordset, rsHeaders As ADODB.Recordset, b As Boolean, sFile As String, shName As String, strSQL As String, iCol As Long
sFile = ThisWorkbook.Path & "\Sample.xlsx"
'shName = "Sheet1"
Dim rsData As ADODB.Recordset
Set cn = New ADODB.Connection
cn.Open ConnectionString:="Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & sFile & "';" & "Extended Properties=""Excel 12.0;HDR=YES;IMEX=1;"";"
'--------
Set ws = ThisWorkbook.ActiveSheet
Set rs = cn.OpenSchema(20)
Do While Not rs.EOF
sName = rs.Fields("Table_Name")
If Right(sName, 14) <> "FilterDatabase" Then
sName = Left(sName, Len(sName) - 1)
'Debug.Print sName
b = False
strSQL = "SELECT * FROM [" & sName & "$]"
Set rsHeaders = New ADODB.Recordset
rsHeaders.Open Source:=strSQL, ActiveConnection:=cn, Options:=1
For iCol = 0 To rsHeaders.Fields.Count - 1
'Debug.Print rsHeaders.Fields(iCol).Name
For Each e In Array("Ref No", "Reference", "Number")
If e = rsHeaders.Fields(iCol).Name Then
b = True: Exit For
End If
Next e
If b Then Exit For
Next iCol
If b Then
'Debug.Print e
strSQL = "SELECT [" & e & "] FROM [" & sName & "$]"
Set rsData = New ADODB.Recordset
Set rsData = cn.Execute(strSQL)
ws.Range("A" & ws.Cells(Rows.Count, 1).End(xlUp).Row + 1).CopyFromRecordset rsData
rsData.Close
'here I am stuck of how to get the data from the found column
End If
'rs.Close
End If
rs.MoveNext
Loop
'rs.Close
'------------------
' strSQL = "SELECT * FROM [" & shName & "$]"
' Set rs = New ADODB.Recordset
' Set rs = cn.Execute(strSQL)
' Range("A1").CopyFromRecordset rs
rs.Close: Set rs = Nothing
cn.Close: Set cn = Nothing
End Sub
【问题讨论】:
-
@Siddharth Rout 您能帮我将代码转换为公共过程吗,因为代码将在多个工作簿上执行?我需要更简洁的代码,而且我比我更信任你(因为我对我的方法有点困惑,因为这个 ADODB 对我来说是新的)