I am writing a macro to move data from a CSV to an excel template. Currently, I have the code set to search for a keyword in column A of the CSV, and extract data from specified columns in the keywords row. I would like to know if there is something I can do to simplify the code.
Public Sub MoveData()
'**defines the project name as a variable
Dim fileName As String
fileName = Worksheets("Cover").Range("B5").Value
'**defines the path of the CSV summary from BlueBeam
Dim path As String
path = "C:\Users\(users)\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 cmdOpen1 As Boolean
cmdOpen1 = False
Dim cmdOpen2 As Boolean
cmdOpen2 = False
For Each subCell In myRange
If subCell Like "*keyword1*" Then
strQuery = "SELECT [Measurement] FROM [" & fileName & "$] Where Subject = '" & subCell.Value & "'"
Set cmd1 = New ADODB.Command
With cmd1
.ActiveConnection = cn
.CommandText = strQuery
End With
Dim rst1 As New ADODB.Recordset
With rst1
If cmdOpen1 = False Then
.Open cmd1
cmdOpen1 = True
End If
End With
currentWB.Worksheets("Bms").Range("C7").CopyFromRecordset rst1
ElseIf subCell Like "*keyword2*" Then
strQuery = "SELECT [Notes (C)], [Col Top (C)], [Col Base (C)] FROM [" & fileName & "$] Where Subject = '" & subCell.Value & "'"
Set cmd2 = New ADODB.Command
With cmd2
.ActiveConnection = cn
.CommandText = strQuery
End With
Dim rst2 As New ADODB.Recordset
With rst2
If cmdOpen2 = False Then
.Open cmd2
cmdOpen2 = True
End If
End With
currentWB.Worksheets("Cols").Range("B7").CopyFromRecordset rst2
End If
Next subCell
openWB.Close
rst1.Close
rst2.Close
End Sub
I'm fairly new to VBA and extremely new to recordsets, so please let me know if you notice anything that should be changed. In total, I will be writing the code to search for about 6-7 keywords and the columns that the data will change based on the keyword. I'd like to revise this code before I move forward with adding more data selection.
If you need anymore information on what I am trying to accomplish or how I coded an area, please let me know. Any help will be greatly appreciated.
