我有2个excel工作簿,并且我将数据(A1:C5)从一个(WB1)拉到另一个,而不使用下面的宏打开源WB。在将数据粘贴到目标工作簿之前,我需要在记录集中过滤数据。 过滤器是删除列“C”中的任何记录=“否” 我怎样才能做到这一点 ? 以下是我正在使用的代码:
Sub TransferData___()
Dim sourceFile As Variant
sourceFile = "C:\WB1.xlsx"
GetData sourceFile, "Sheet1", "A1:C5", Sheets("Sheet1").Range("A1")
End Sub
Public Sub GetData(sourceFile As Variant, SourceSheet As String, _
SourceRange As String, TargetRange As Range)
Dim rsCon As Object
Dim rsData As Object
Dim szConnect As String
Dim szSQL As String
Dim lCount As Long
' Create the connection string.
If Val(Application.Version) < 12 Then
szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sourceFile & ";" & _
"Extended Properties=""Excel 8.0;HDR=No"";"
Else
szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & sourceFile & ";" & _
"Extended Properties=""Excel 12.0;HDR=No"";"
End If
szSQL = "SELECT * FROM [" & SourceSheet$ & "$" & SourceRange$ & "];"
Set rsCon = CreateObject("ADODB.Connection")
Set rsData = CreateObject("ADODB.Recordset")
rsCon.Open szConnect 'here the file is opened in the background
rsData.Open szSQL, rsCon, 0, 1, 1 'read data
TargetRange.Cells(1, 1).CopyFromRecordset rsData
' Clean up our Recordset object.
rsData.Close
Set rsData = Nothing
rsCon.Close
Set rsCon = Nothing
Exit Sub
End Sub
答案 0 :(得分:0)
在select语句中排除不需要的记录更为典型:
{width: 40}
如果要查询的数据没有标题行,则F1,F2,F3等是默认字段名称。