如何在用于跨工作簿传输数据的VBA宏中查询特定列?
我正在使用Excel宏,通过遵循以下准则,在使用ADO的works之间传输数据。目前,我已将代码设置为在源文件的a列中搜索关键字。一旦找到关键字,它将从整行复制数据。但是,我只需要G-I列中的数据,无法找到压缩数据选择的信息如何在用于跨工作簿传输数据的VBA宏中查询特定列?,vba,excel,Vba,Excel,我正在使用Excel宏,通过遵循以下准则,在使用ADO的works之间传输数据。目前,我已将代码设置为在源文件的a列中搜索关键字。一旦找到关键字,它将从整行复制数据。但是,我只需要G-I列中的数据,无法找到压缩数据选择的信息 Public Sub MoveData() 'defines the project name as a variable Dim fileName As String fileName = Worksheets("Cover").Ran
Public Sub MoveData()
'defines the project name as a variable
Dim fileName As String
fileName = Worksheets("Cover").Range("B5").Value
'defines the path
Dim path As String
path = "C:\Users\(user)\Documents\(folder)\" & fileName & ".csv"
'defines the two workbooks that the data will move between
Dim currentWB As Workbook
Set currentWB = ThisWorkbook
Dim openWB As Workbook
Set openWB = Workbooks.Open(path)
Dim openWs As Worksheet
Set openWs = openWB.Sheets(fileName)
'connects using ADODB to transfer the data
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & path & ";" & _
"Extended Properties=Excel 12.0 Xml;"
.Open
End With
'selects the first column to be read and sorted
Dim subCell As Range
Dim myRange As Range
Set myRange = Range("A1:A500")
Dim cmdOpen As Boolean
cmdOpen = False
For Each subCell In myRange
'searches for the column markups
If subCell Like "*COLUMN*" Then
strQuery = "SELECT * FROM [" & fileName & "$] Where Subject = '" & subCell.Value & "'"
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = cn
.CommandText = strQuery
End With
Dim rst As New ADODB.Recordset
With rst
If cmdOpen = False Then
.Open cmd
cmdOpen = True
End If
End With
currentWB.Worksheets("Cols").Range("B7:D7").CopyFromRecordset rst
End If
Next subCell
openWB.Close
End Sub
这个strQuery=SELECT*FROM[&fileName&$],其中Subject='&subCell.Value&'是我所指的行。它选择找到关键字的数据行。我想将此选择限制在G-I列。如能就如何完成此操作提供任何建议,将不胜感激。您知道列标题吗?如果是,请指定它们,而不是*使用从[&fileName&$]中选择[Column 1],[Column 2],其中Subject='&subCell.Value&'而不是*[Column 1],[Column 2]正是我要查找的列标题。谢谢你的快速帮助。