How to dynamically refer to a Referenced Table when looping through sheets?

Pteroglossus

New Member
Joined
Nov 19, 2020
Messages
14
Office Version
  1. 365
Platform
  1. Windows
Hi,

I' ve been working on a VBA script to automate a series of action I have to take on daily generated .csv files structured as follows:

The raw data is located in colums A to H, the script adds a "remark" column in I and then pastes various Countifs formulas in column J to AL.

The number of rows varies daily.

Using bits of code I found here and there, I've been able to write 7 steps but I'm now really stuck. Here is what I have so far:

Excel Formula:
Sub Csv_proccessing_sequence()
    Dim xFilesToOpen As Variant
    Dim i As Integer
    Dim xWb As Workbook
    Dim xTempWb As Workbook
    Dim xDelimiter As String
    Dim xScreen As Boolean
    Dim sourceColumn As Range, targetColumn As Range
    Dim lastRow As Long
    Dim lastColumn As Long
    Dim Rtable As ListObject
    Dim TblRng As Range
 '1 - import csv file
    On Error GoTo ErrHandler
    xScreen = Application.ScreenUpdating
    Application.ScreenUpdating = False
    xDelimiter = ":"
    xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Kutools for Excel", , True)
    If TypeName(xFilesToOpen) = "Boolean" Then
        MsgBox "No files were selected", , "Kutools for Excel"
        GoTo ExitHandler
    End If
    i = 1
    Set xTempWb = Workbooks.Open(xFilesToOpen(i))
    xTempWb.Sheets(1).Copy
    Set xWb = Application.ActiveWorkbook
    xTempWb.Close False
    xWb.Worksheets(i).Columns("A").TextToColumns _
      Destination:=Range("A1"), DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, _
      ConsecutiveDelimiter:=False, _
      Tab:=False, Semicolon:=False, _
      Comma:=False, Space:=False, _
      Other:=True, OtherChar:=xDelimiter
'2 - delete columns D and I
      Range("D:D,I:I").Delete
'3 - Add header column I
      Cells(1, 9).Value = "Obs"
'4- Copy columns from Formula tab
      Set sourceColumn = Workbooks("Import_txt_.xlsm").Worksheets(2).Columns("J:AM")
      Set targetColumn = xWb.Worksheets(1).Columns("J:AM")
      sourceColumn.Copy Destination:=targetColumn
    targetColumn.ColumnWidth = sourceColumn.ColumnWidth
'5 - Define lastrow and last column and copy all formulas down
      lastRow = Cells(Rows.Count, "B").End(xlUp).Row
      lastColumn = Cells(Columns.Count).End(xlToLeft).Column
      Range("J4:AM4").Select
      Selection.AutoFill Destination:=Range("J4:AM" & lastRow), Type:=xlFillCopy
'6 - Center all cells
    With xWb.Worksheets(i).Cells
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
'7 - Turn into a referenced table
    With xWb.Worksheets(i)
    Set TblRng = .Range("A1", .Cells(lastRow, lastColumn))
    Set Rtable = .ListObjects.Add(xlSrcRange, TblRng, , xlYes)
    End With

'8 - 'Add "Total" and drag sum right

    Rtable.ShowTotals = True
    Rtable.ListColumns("Arr IFR").TotalsCalculation = xlTotalsCalculationSum
    Range("Tableau1[[#Totals],[Arr IFR]]").Select
    Selection.AutoFill Destination:=Range( _
        "Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]"), Type:=xlFillDefault
    Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]").Select
    Selection.Font.Size = 20
    Selection.Font.Bold = True

' 9- loop
    Do While i < UBound(xFilesToOpen)
        i = i + 1
        Set xTempWb = Workbooks.Open(xFilesToOpen(i))
        With xWb
            xTempWb.Sheets(1).Move after:=.Sheets(.Sheets.Count)
            .Worksheets(i).Columns("A:A").TextToColumns _
              Destination:=Range("A1"), DataType:=xlDelimited, _
              TextQualifier:=xlDoubleQuote, _
              ConsecutiveDelimiter:=False, _
              Tab:=False, Semicolon:=False, _
              Comma:=False, Space:=False, _
              Other:=True, OtherChar:=xDelimiter
        'delete columns D and I
              Range("D:D,I:I").Delete
        'Add header column I
              Cells(1, 9).Value = "Obs"
        'Copy column from Formula tab
              Set sourceColumn = Workbooks("Import_txt_.xlsm").Worksheets(2).Columns("J:AM")
              Set targetColumn = xWb.Worksheets(i).Columns("J:AM")
              sourceColumn.Copy Destination:=targetColumn
        'Define lastrow and copy all formulas down
                lastRow = Cells(Rows.Count, "B").End(xlUp).Row
                lastColumn = Cells(Columns.Count).End(xlToLeft).Column
                Range("J4:AM4").Select
                Selection.AutoFill Destination:=Range("J4:AM" & lastRow), Type:=xlFillCopy
        'Center all cells
            With xWb.Worksheets(i).Cells
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
            End With
        'Turn into a table
            With xWb.Worksheets(i)
            Set TblRng = .Range("A1", .Cells(lastRow, lastColumn))
            Set Table = .ListObjects.Add(xlSrcRange, TblRng, , xlYes)
            Table.Name = "DynTable"
            End With
        'Display "total" line and drag sum formula right + font size
            
            Rtable.ShowTotals = True
            Rtable.ListColumns("Arr IFR").TotalsCalculation = _
                xlTotalsCalculationSum
            Range("Table, [[#Totals][Arr IFR]]").Select
            Selection.AutoFill Destination:=Range( _
                "Tableau(i)[[#Totals],[Arr IFR]:[TDP/RDG]]"), Type:=xlFillDefault
            Range("Tableau(i)[[#Totals],[Arr IFR]:[TDP/RDG]]").Select
            Selection.Font.Size = 20
        
    End With
    Loop
ExitHandler:
    Application.ScreenUpdating = xScreen
    Set xWb = Nothing
    Set xTempWb = Nothing
    Exit Sub
ErrHandler:
    MsgBox Err.Description, , "Kutools for Excel"
    Resume ExitHandler
End Sub

The "Add total…" remark line is where I'm stuck. Using the macro recording tool, the code given works for the first iteration of script, but won’t work the loop part, as “Tableau1” will become “Tableau2” and so on.

I’ve been trying to refer to the table dynamically using the variables “Rtable” and “TabRng”, but either it’s not possible or I can’t get the syntax right.

Could anyone give me a hint?

Also, if you see anything else that could be improved please let me know

Best,
KL
 
Without seeing it in operation, I may not be able to nail it down but here's some help on other things to reduce opportunity for confusion. A little bit of training on cleaning up your code
I think the issue is in here:
VBA Code:
'8 - 'Add "Total" and drag sum right
'   Tableau1 needs to become dynamic, not specified
    Rtable.ShowTotals = True
    Rtable.ListColumns("Arr IFR").TotalsCalculation = xlTotalsCalculationSum
    Range("Tableau1[[#Totals],[Arr IFR]]").AutoFill Destination:=Range( _
        "Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]"), Type:=xlFillDefault
    With Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]")
        With .Font
            .Size = 20
            .Bold = True
        End With
    End With
Here's some modified stuff of yours...
VBA Code:
Sub Csv_proccessing_sequence()
'   Compress your code. You only need to use one dimension line in total
    Dim xFilesToOpen As Variant, i As Integer, xWb As Workbook, xTempWb As Workbook, xDelimiter As String, _
        xScreen As Boolean, sourceColumn As Range, targetColumn As Range, lastRow As Long, lastColumn As Long, _
        Rtable As ListObject, TblRng As Range
 
    On Error GoTo ErrHandler '    Smart move. Develop it a bit more so your error handler is a private sub that any sub can use and you don't repeat it the code.

'1 - import csv file
    xScreen = Application.ScreenUpdating
    Application.ScreenUpdating = False
    xDelimiter = InputBox("What is your specified delimiter?", "Delimiter specification", ":")
    xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Kutools for Excel", , True)
    If TypeName(xFilesToOpen) = "Boolean" Then
        MsgBox "No files were selected", , "Kutools for Excel"
        GoTo ExitHandler
    End If
    i = 1
    Set xTempWb = Workbooks.Open(xFilesToOpen(i))
    xTempWb.Sheets(1).Copy
    Set xWb = Application.ActiveWorkbook
    xTempWb.Close False
    xWb.Worksheets(i).Columns("A").TextToColumns _
      Destination:=Range("A1"), DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, _
      Other:=True, OtherChar:=xDelimiter
'2 - delete columns D and I
      Range("D:D,I:I").Delete
'3 - Add header column I
      Cells(1, 9).Value = "Obs"
'4- Copy columns from Formula tab
      Set sourceColumn = Workbooks("Import_txt_.xlsm").Worksheets(2).Columns("J:AM")
      Set targetColumn = xWb.Worksheets(1).Columns("J:AM")
      sourceColumn.Copy Destination:=targetColumn
    targetColumn.ColumnWidth = sourceColumn.ColumnWidth
'5 - Define lastrow and last column and copy all formulas down
      lastRow = Cells(Rows.Count, "B").End(xlUp).Row
      lastColumn = Cells(Columns.Count).End(xlToLeft).Column
      Range("J4:AM4").Select
      Selection.AutoFill Destination:=Range("J4:AM" & lastRow), Type:=xlFillCopy
'6 - Center all cells
    With xWb.Worksheets(i).Cells
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
'7 - Turn into a referenced table
    With xWb.Worksheets(i)
    Set TblRng = .Range("A1", .Cells(lastRow, lastColumn))
    Set Rtable = .ListObjects.Add(xlSrcRange, TblRng, , xlYes)
    End With

'8 - 'Add "Total" and drag sum right

    Rtable.ShowTotals = True
    Rtable.ListColumns("Arr IFR").TotalsCalculation = xlTotalsCalculationSum
    Range("Tableau1[[#Totals],[Arr IFR]]").AutoFill Destination:=Range( _
        "Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]"), Type:=xlFillDefault
    With Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]")
        With .Font
            .Size = 20
            .Bold = True
        End With
    End With

' 9- loop
    Do While i < UBound(xFilesToOpen)
        i = i + 1
        Set xTempWb = Workbooks.Open(xFilesToOpen(i))
        '   Condense your code by removing False settings that don't change an aleady false condition
        With xWb
            xTempWb.Sheets(1).Move after:=.Sheets(.Sheets.Count)
            .Worksheets(i).Columns("A:A").TextToColumns _
              Destination:=Range("A1"), DataType:=xlDelimited, _
              TextQualifier:=xlDoubleQuote, Other:=True, OtherChar:=xDelimiter
        '   REMOVED POINTLESS FALSE SETTINGS
        ' "_
        '     ConsecutiveDelimiter:=False, _
              Tab:=False, Semicolon:=False, _
              Comma:=False, Space:=False, _"
        'delete columns D and I
Stop
        With ActiveSheet 'Check this is correct
              .Columns("I", "D").Delete 'Order is important or target column name changes
        'Add header column I
              Cells(1, 9).Text = "Obs"

        'Copy column from Formula tab
              Set sourceColumn = Workbooks("Import_txt_.xlsm").Worksheets(2).Columns("J:AM")
              Set targetColumn = xWb.Worksheets(i).Columns("J:AM")
              sourceColumn.Copy Destination:=targetColumn

        'Define lastrow and copy all formulas down
                lastRow = Cells(Rows.Count, "B").End(xlUp).Row
                lastColumn = Cells(Columns.Count).End(xlToLeft).Column
                Range("J4:AM4").AutoFill Destination:=Range("J4:AM" & lastRow), Type:=xlFillCopy

        'Center all cells
            With xWb.Worksheets(i).Cells
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
            End With

        'Turn into a table
            With xWb.Worksheets(i)
                Set TblRng = .Range("A1", .Cells(lastRow, lastColumn))
                Set Table = .ListObjects.Add(xlSrcRange, TblRng, , xlYes)
                Table.Name = "DynTable"
            End With

        'Display "total" line and drag sum formula right + font size

            With Rtable
                .ShowTotals = True
                .ListColumns("Arr IFR").TotalsCalculation = xlTotalsCalculationSum
            End With
            'The following could be edited to a few lines instead of a wall of code
        '   Range("Table, [[#Totals][Arr IFR]]").Select
        '   Selection.AutoFill Destination:=Range( _
        '    "Tableau(i)[[#Totals],[Arr IFR]:[TDP/RDG]]"), Type:=xlFillDefault
        '     Range("Tableau(i)[[#Totals],[Arr IFR]:[TDP/RDG]]").Select
        '   Selection.Font.Size = 20
        ' as demonstrated below...
            Range("Table, [[#Totals][Arr IFR]]").AutoFill Destination:=Range("Tableau(i)[[#Totals],[Arr IFR]:[TDP/RDG]]"), _
                Type:=xlFillDefault
            Range("Tableau(i)[[#Totals],[Arr IFR]:[TDP/RDG]]").Font.Size = 20
        '   Wherever you see
        '       xnn.select followed by
        '       selection.nnnx
        '   you can remove "select...selection." entirely without affecting function
        '   but improve execution speed and reduce memory overhead. to result in "xnn.nnnx" instead

        End With
    Loop
ExitHandler:
    xScreen = True
    Set xWb = ""
    Set xTempWb = ""
    Exit Sub '"Exit" or "Exit Sub"? They have slightly different functions from call procedures in other modules
ErrHandler:
    MsgBox Err.Description, , "Kutools for Excel"
    Resume ExitHandler
End Sub
 
Last edited:
Upvote 0
Thanks for the tips and suggestions. I tried to apply them as much as I could to tidy up the code.

The sequence still works until step 16. The first table created is named "Tableau1", but after the first loop, the subsequent tables in the next sheets are named"Tableau2"... 3 and so on, which prevents the autofill from pasting the formulas.

Is there a way to dynamically name the subsequent Tables similar to what is done at step 9 with the sheets (i= i+1 -> xWb.worksheets(i) so that I could refer to the table as Tableau(i) in the code and solve the issue?

Excel Formula:
Sub Csv_proc_sequence()

    Dim xFilesToOpen As Variant, i As Integer, xWb As Workbook, xTempWb As Workbook, xDelimiter As String, _
        xScreen As Boolean, sourceColumn As Range, targetColumn As Range, lastRow As Long, lastColumn As Long, _
        Rtable As ListObject, TblRng As Range
        
On Error GoTo ErrHandler

 '1 - import csv file

    xScreen = Application.ScreenUpdating
    Application.ScreenUpdating = False
    xDelimiter = ":"
    xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Open text/csv file", , True)
    If TypeName(xFilesToOpen) = "Boolean" Then
        MsgBox "No files were selected", , "Error"
        GoTo ExitHandler
    End If
    i = 1
    Set xTempWb = Workbooks.Open(xFilesToOpen(i))
    xTempWb.Sheets(1).Copy
    Set xWb = Application.ActiveWorkbook
    xTempWb.Close False
    xWb.Worksheets(i).Columns("A").TextToColumns _
      Destination:=Range("A1"), DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, Other:=True, OtherChar:=xDelimiter
'2 - delete columns D and I ( If I start a "With ActiveSheet" here, I get a "Loop without Do" error)
      Range("D:D,I:I").Delete
'3 - Add header column I
      Cells(1, 9).Value = "Obs"
'4- Copy columns from Formula tab
      Set sourceColumn = Workbooks("Import_txt_.xlsm").Worksheets(2).Columns("J:AM")
      Set targetColumn = xWb.Worksheets(1).Columns("J:AM")
      sourceColumn.Copy Destination:=targetColumn
    targetColumn.ColumnWidth = sourceColumn.ColumnWidth
'5 - Define lastrow and last column and copy all formulas down
      lastRow = Cells(Rows.Count, "B").End(xlUp).Row
      lastColumn = Cells(Columns.Count).End(xlToLeft).Column
      Range("J4:AM4").AutoFill Destination:=Range("J4:AM" & lastRow), Type:=xlFillCopy
'6 - Center all cells
    With xWb.Worksheets(i).Cells
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
'7 - Turn into a referenced table
    With xWb.Worksheets(i)
    Set TblRng = .Range("A1", .Cells(lastRow, lastColumn))
    Set Rtable = .ListObjects.Add(xlSrcRange, TblRng, , xlYes)
    End With

'8 - 'Add "Total" and drag sum right

    Rtable.ShowTotals = True
    Rtable.ListColumns("Arr IFR").TotalsCalculation = xlTotalsCalculationSum
    Range("Tableau1[[#Totals],[Arr IFR]]").AutoFill Destination:=Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]"), Type:=xlFillDefault
    Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]").Font.Size = 20
    Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]").Font.Bold = True

' 9- loop
    Do While i < UBound(xFilesToOpen)
        i = i + 1
        Set xTempWb = Workbooks.Open(xFilesToOpen(i))
        With xWb
            xTempWb.Sheets(1).Move after:=.Sheets(.Sheets.Count)
            .Worksheets(i).Columns("A:A").TextToColumns _
              Destination:=Range("A1"), DataType:=xlDelimited, _
              TextQualifier:=xlDoubleQuote, _
              Other:=True, OtherChar:=xDelimiter
        '10- delete columns D and I
              Range("D:D,I:I").Delete
        '11 - Add header column I
              Cells(1, 9).Value = "Obs"
        '12 - Copy column from Formula tab
              Set sourceColumn = Workbooks("Import_txt_.xlsm").Worksheets(2).Columns("J:AM")
              Set targetColumn = xWb.Worksheets(i).Columns("J:AM")
              sourceColumn.Copy Destination:=targetColumn
        '13 - Define lastrow and copy all formulas down
                lastRow = Cells(Rows.Count, "B").End(xlUp).Row
                lastColumn = Cells(Columns.Count).End(xlToLeft).Column
                Range("J4:AM4").Select
                Selection.AutoFill Destination:=Range("J4:AM" & lastRow), Type:=xlFillCopy
        '14 - Center all cells
            With xWb.Worksheets(i).Cells
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
            End With
        '15 - Turn into a table
            With xWb.Worksheets(i)
            Set TblRng = .Range("A1", .Cells(lastRow, lastColumn))
            Set Rtable = .ListObjects.Add(xlSrcRange, TblRng, , xlYes)
            End With
        '16 - Display "total" line and drag sum formula right + font size
        Rtable.ShowTotals = True
        Rtable.ListColumns("Arr IFR").TotalsCalculation = xlTotalsCalculationSum
        Range("Tableau1[[#Totals],[Arr IFR]]").AutoFill Destination:=Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]"), Type:=xlFillDefault
        Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]").Font.Size = 20
        Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]").Font.Bold = True
        
    End With
    Loop
ExitHandler:
    Application.ScreenUpdating = xScreen
    Set xWb = Nothing
    Set xTempWb = Nothing
    Exit Sub
ErrHandler:
    MsgBox Err.Description, , "Error"
    Resume ExitHandler
End Sub
 
Upvote 0
I've been thinking...I don't need to use the built-in "total" line at the bottom of the table. I can just use a simple SUM formula with dynamic references:

Excel Formula:
Dim LRow As Long

LRow = Cells(Rows.Count, 4).End(xlUp).Row

Range("J" & LRow + 1).FormulaR1C1 = "=SUM(R[-" & LRow & "]C:R[-1]C)"

Range("J" & LRow + 1).Select

 Selection.AutoFill Destination:=Range("J:AI" & LRow), Type:=xlFillCopy ' Runtime error 1004. Method Range of object_global failed

The SUM formula is written to the right cell, "J41" in this case, but I CAN'T get the Autofill to drag it to AI & LRow.

Could someone help me with the syntax?
 
Upvote 0
Does this help?
VBA Code:
 Dim LRow As Long,ws As Worksheet

    ' Set the worksheet reference
    Set ws = ThisWorkbook.Sheets("Sheet1") ' Adjust sheet name if necessary

    ' Find the last row in column D (4th column)
    LRow = ws.Cells(ws.Rows.Count, 4).End(xlUp).Row

    ' Set the formula in the cell in column J (next row after the last data row)
    with ws.Range("J" & LRow + 1)
        .FormulaR1C1 = "=SUM(R[-" & LRow & "]C:R[-1]C)"
        ' Select the cell where the formula is placed (optional)
        .Select
        ' AutoFill the formula to the range J to AI for the last row
        .AutoFill Destination:=ws.Range("J" & LRow + 1 & ":AI" & LRow + 1), Type:=xlFillCopy
 
Upvote 0
Solution
Well thanks, but unfortunately it doesn't work... I believe there an issue with the definition of "ws". I get various error messages...in French, if it can help I can roughly translate them.

Excel Formula:
    Set ws = xWb.Worksheets(i) ' I also tried with xWb.Worksheets(1), xWb.Worksheets("sheets1") , xTempWb.Worksheets("sheets1") 

    ' Find the last row in column D (4th column)
    LRow = ws.Cells(ws.Rows.Count, 4).End(xlUp).Row

    ' Set the formula in the cell in column J (next row after the last data row)
    With ws.Range("J" & LRow + 1)
        .FormulaR1C1 = "=SUM(R[-" & LRow & "]C:R[-1]C)"
        ' Select the cell where the formula is placed (optional)
        .Select
        ' AutoFill the formula to the range J to AI for the last row
        .AutoFill Destination:=ws.Range("J" & LRow + 1 & ":AI" & LRow + 1), Type:=xlFillCopy
        
    End With

Here is my whole code if it can help:

Excel Formula:
Sub Csv_proc_sequence_test()

    Dim xFilesToOpen As Variant, i As Integer, xWb As Workbook, xTempWb As Workbook, xDelimiter As String, _
        xScreen As Boolean, sourceColumn As Range, targetColumn As Range, lastRow As Long, lastColumn As Long, _
        Rtable As ListObject, TblRng As Range, LRow As Range, ws As Worksheet
        
        
On Error GoTo ErrHandler

 '1 - import csv file

    xScreen = Application.ScreenUpdating
    Application.ScreenUpdating = False
    xDelimiter = ":"
    xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Open text/csv file", , True)
    If TypeName(xFilesToOpen) = "Boolean" Then
        MsgBox "No files were selected", , "Error"
        GoTo ExitHandler
    End If
    i = 1
    Set xTempWb = Workbooks.Open(xFilesToOpen(i))
    xTempWb.Sheets(1).Copy
    Set xWb = Application.ActiveWorkbook
    xTempWb.Close False
    xWb.Worksheets(i).Columns("A").TextToColumns _
      Destination:=Range("A1"), DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, Other:=True, OtherChar:=xDelimiter
'2 - delete columns D and I ( If I start a "With ActiveSheet" here, I get a "Loop without Do" error)
      Range("D:D,I:I").Delete
'3 - Add header column I
      Cells(1, 9).Value = "Obs"
'4- Copy columns from Formula tab
      Set sourceColumn = Workbooks("Import_txt_.xlsm").Worksheets(2).Columns("J:AM")
      Set targetColumn = xWb.Worksheets(1).Columns("J:AM")
      sourceColumn.Copy Destination:=targetColumn
    targetColumn.ColumnWidth = sourceColumn.ColumnWidth
'5 - Define lastrow and last column and copy all formulas down
      lastRow = Cells(Rows.Count, "B").End(xlUp).Row
      lastColumn = Cells(Columns.Count).End(xlToLeft).Column
      Range("J4:AM4").AutoFill Destination:=Range("J4:AM" & lastRow), Type:=xlFillCopy
'6 - Center all cells
    With xWb.Worksheets(i).Cells
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
'7 - Turn into a referenced table
    With xWb.Worksheets(i)
    Set TblRng = .Range("A1", .Cells(lastRow, lastColumn))
    Set Rtable = .ListObjects.Add(xlSrcRange, TblRng, , xlYes)
End With

    ' Set the worksheet reference
    Set ws = xWb.Worksheets(i) ' Adjust sheet name if necessary

    ' Find the last row in column D (4th column)
    LRow = ws.Cells(ws.Rows.Count, 4).End(xlUp).Row

    ' Set the formula in the cell in column J (next row after the last data row)
    With ws.Range("J" & LRow + 1)
        .FormulaR1C1 = "=SUM(R[-" & LRow & "]C:R[-1]C)"
        ' Select the cell where the formula is placed (optional)
        .Select
        ' AutoFill the formula to the range J to AI for the last row
        .AutoFill Destination:=ws.Range("J" & LRow + 1 & ":AI" & LRow + 1), Type:=xlFillCopy
        
    End With

' 9- loop
    Do While i < UBound(xFilesToOpen)
        i = i + 1
        Set xTempWb = Workbooks.Open(xFilesToOpen(i))
        With xWb
            xTempWb.Sheets(1).Move after:=.Sheets(.Sheets.Count)
            .Worksheets(i).Columns("A:A").TextToColumns _
              Destination:=Range("A1"), DataType:=xlDelimited, _
              TextQualifier:=xlDoubleQuote, _
              Other:=True, OtherChar:=xDelimiter
        '10- delete columns D and I
              Range("D:D,I:I").Delete
        '11 - Add header column I
              Cells(1, 9).Value = "Obs"
        '12 - Copy column from Formula tab
              Set sourceColumn = Workbooks("Import_txt_.xlsm").Worksheets(2).Columns("J:AM")
              Set targetColumn = xWb.Worksheets(i).Columns("J:AM")
              sourceColumn.Copy Destination:=targetColumn
        '13 - Define lastrow and copy all formulas down
                lastRow = Cells(Rows.Count, "B").End(xlUp).Row
                lastColumn = Cells(Columns.Count).End(xlToLeft).Column
                Range("J4:AM4").Select
                Selection.AutoFill Destination:=Range("J4:AM" & lastRow), Type:=xlFillCopy
        '14 - Center all cells
            With xWb.Worksheets(i).Cells
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
            End With
        '15 - Turn into a table
            With xWb.Worksheets(i)
            Set TblRng = .Range("A1", .Cells(lastRow, lastColumn))
            Set Rtable = .ListObjects.Add(xlSrcRange, TblRng, , xlYes)
            End With
        '16 - Display "total" line and drag sum formula right + font size
        Rtable.ShowTotals = True
        Rtable.ListColumns("Arr IFR").TotalsCalculation = xlTotalsCalculationSum
        Range("Tableau1[[#Totals],[Arr IFR]]").AutoFill Destination:=Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]"), Type:=xlFillDefault
        Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]").Font.Size = 20
        Range("Tableau1[[#Totals],[Arr IFR]:[TDP/RDG]]").Font.Bold = True
        
    End With
    Loop
ExitHandler:
    Application.ScreenUpdating = xScreen
    Set xWb = Nothing
    Set xTempWb = Nothing
    Exit Sub
ErrHandler:
    MsgBox Err.Description, , "Error"
    Resume ExitHandler
End Sub
 
Upvote 0
If I isolate your code in an independent macro and apply it on a separate sheet it does work when I use this:

Excel Formula:
Sub test_totals()
 
 Dim LRow As Long, ws As Worksheet

    ' Set the worksheet reference
    Set ws = ThisWorkbook.ActiveSheet  ' Adjust sheet name if necessary

    ' Find the last row in column D (4th column)
    LRow = ws.Cells(ws.Rows.Count, 4).End(xlUp).Row

    ' Set the formula in the cell in column J (next row after the last data row)
    With ws.Range("J" & LRow + 1)
        .FormulaR1C1 = "=SUM(R[-" & LRow & "]C:R[-1]C)"
        ' Select the cell where the formula is placed (optional)
        .Select
        ' AutoFill the formula to the range J to AI for the last row
        .AutoFill Destination:=ws.Range("J" & LRow + 1 & ":AI" & LRow + 1), Type:=xlFillCopy
      
        End With
End Sub

Whenever I try to include it in my code it fails. It really seems the "ws" reference interferes with something else in the existing code.

Any further idea? I really need this to work.
 
Upvote 0
I got it to work!! Finally! I reused the lastRow variable used in step 5 and used your code for the Autofill in step 8.

I also removed any reference to worksheets and therefore didn't use any "With" block.

If anyone could explain to me what went wrong, I'd be happy to try and understand. Here is the final code:

Excel Formula:
Sub Csv_proc_sequence_working()

    Dim xFilesToOpen As Variant, i As Integer, xWb As Workbook, xTempWb As Workbook, xDelimiter As String, _
        xScreen As Boolean, sourceColumn As Range, targetColumn As Range, lastRow As Long, lastColumn As Long, _
        Rtable As ListObject, TblRng As Range
        
        
On Error GoTo ErrHandler

 '1 - import csv file

    xScreen = Application.ScreenUpdating
    Application.ScreenUpdating = False
    xDelimiter = ":"
    xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Open text/csv file", , True)
    If TypeName(xFilesToOpen) = "Boolean" Then
        MsgBox "No files were selected", , "Error"
        GoTo ExitHandler
    End If
    i = 1
    Set xTempWb = Workbooks.Open(xFilesToOpen(i))
    xTempWb.Sheets(1).Copy
    Set xWb = Application.ActiveWorkbook
    xTempWb.Close False
    xWb.Worksheets(i).Columns("A").TextToColumns _
      Destination:=Range("A1"), DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, Other:=True, OtherChar:=xDelimiter
'2 - delete columns D and I ( If I start a "With ActiveSheet" here, I get a "Loop without Do" error)
      Range("D:D,I:I").Delete
'3 - Add header column I
      Cells(1, 9).Value = "Obs"
'4- Copy columns from Formula tab
      Set sourceColumn = Workbooks("Import_txt_.xlsm").Worksheets(2).Columns("J:AM")
      Set targetColumn = xWb.Worksheets(1).Columns("J:AM")
      sourceColumn.Copy Destination:=targetColumn
    targetColumn.ColumnWidth = sourceColumn.ColumnWidth
'5 - Define lastrow and last column and copy all formulas down
      lastRow = Cells(Rows.Count, "B").End(xlUp).Row
      lastColumn = Cells(Columns.Count).End(xlToLeft).Column
      Range("J4:AM4").AutoFill Destination:=Range("J4:AM" & lastRow), Type:=xlFillCopy
      
'6 - Center all cells
    With xWb.Worksheets(i).Cells
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
'7 - Turn into a referenced table
    With xWb.Worksheets(i)
    Set TblRng = .Range("A1", .Cells(lastRow, lastColumn))
    Set Rtable = .ListObjects.Add(xlSrcRange, TblRng, , xlYes)
End With

'8 - Copy "Sum" Formula in "J" + lastrow
        Range("J" & lastRow + 1).FormulaR1C1 = "=SUM(R[-" & lastRow & "]C:R[-1]C)"
        Range("J" & lastRow + 1).AutoFill Destination:=Range("J" & lastRow + 1 & ":AI" & lastRow + 1), Type:=xlFillCopy


' 9- loop
    Do While i < UBound(xFilesToOpen)
        i = i + 1
        Set xTempWb = Workbooks.Open(xFilesToOpen(i))
        With xWb
            xTempWb.Sheets(1).Move after:=.Sheets(.Sheets.Count)
            .Worksheets(i).Columns("A:A").TextToColumns _
              Destination:=Range("A1"), DataType:=xlDelimited, _
              TextQualifier:=xlDoubleQuote, _
              Other:=True, OtherChar:=xDelimiter
        '10- delete columns D and I
              Range("D:D,I:I").Delete
        '11 - Add header column I
              Cells(1, 9).Value = "Obs"
        '12 - Copy column from Formula tab
              Set sourceColumn = Workbooks("Import_txt_.xlsm").Worksheets(2).Columns("J:AM")
              Set targetColumn = xWb.Worksheets(i).Columns("J:AM")
              sourceColumn.Copy Destination:=targetColumn
        '13 - Define lastrow and copy all formulas down
                lastRow = Cells(Rows.Count, "B").End(xlUp).Row
                lastColumn = Cells(Columns.Count).End(xlToLeft).Column
                Range("J4:AM4").Select
                Selection.AutoFill Destination:=Range("J4:AM" & lastRow), Type:=xlFillCopy
        '14 - Center all cells
            With xWb.Worksheets(i).Cells
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
            End With
        '15 - Turn into a table
            With xWb.Worksheets(i)
            Set TblRng = .Range("A1", .Cells(lastRow, lastColumn))
            Set Rtable = .ListObjects.Add(xlSrcRange, TblRng, , xlYes)
            End With
        '16 - Copy "Sum" Formula in "J" + lastrow
        Range("J" & lastRow + 1).FormulaR1C1 = "=SUM(R[-" & lastRow & "]C:R[-1]C)"
        Range("J" & lastRow + 1).AutoFill Destination:=Range("J" & lastRow + 1 & ":AI" & lastRow + 1), Type:=xlFillCopy
        
        
    End With
    Loop
ExitHandler:
    Application.ScreenUpdating = xScreen
    Set xWb = Nothing
    Set xTempWb = Nothing
    Exit Sub
ErrHandler:
    MsgBox Err.Description, , "Error"
    Resume ExitHandler
End Sub

Anyways, thank you @Rhodie72 for your help!
 
Upvote 0
when you use with blocks, the variable used during that block step remains unchanged unless you specifically change it within the step
 
Upvote 0

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top