I have the following macro which needs to loop though an Excel-2007 table. The table has several columns and I am currently finding the correct column position using the Index
property columns.
Using the index is the only way I could find to correctly index into the fName
object. The better option I am hoping for is to access specific columns using the Column Name/Header. How can I do this and can this be even done?
Furthermore, in general, is there a better way to construct this loop?
Worksheets("Lists").Select
Dim filesToImport As ListObject
Dim fName As Object
Dim fileNameWithDate As String
Dim newFileColIndex As Integer
Dim newSheetColIndex As Integer
Set filesToImport = ActiveSheet.ListObjects("tblSourceFiles")
newFileColIndex = filesToImport.ListColumns("New File Name").Index // <- Can this be different?
For Each fName In filesToImport.ListRows // Is there a better way?
If InStr(fName.Range(1, col), "DATE") <> 0 Then
// Need to change the ffg line to access by column name
fileNameWithDate = Replace(fName.Range(1, newFileColIndex).value, "DATE", _
Format(ThisWorkbook.names("ValDate").RefersToRange, "yyyymmdd"))
wbName = OpenCSVFIle(fPath & fileNameWithDate)
CopyData sourceFile:=CStr(fileNameWithDate), destFile:=destFile, destSheet:="temp"
End If
Next fName2
If you want to find a specific value in a column heading, you can use the find method. The find method returns a range, which you can then use as a reference to perform the rest of the operation. There are a lot of optional parameter to the find method, read up on it in the help docs if you need to tweak it more.
Dim cellsToSearch As Range
Dim foundColumn As Range
Dim searchValue As String
Set cellsToSearch = Sheet1.Range("A1:D1") ' Set your cells to be examined here
searchValue = "Whatever you're looking for goes here"
Set foundColumn = cellsToSearch.Find(What:=searchValue)