As far as you are studying VBA for 3 days, it is a really good idea to start using the Macro recorder for tasks like this, at least to have a starting point. This is a simple example from the Macro Recorder:
Sub Makro1()
'
' Makro1 Makro
'
'
Cells.Clear
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$E$13"), , xlNo).Name = _
"Table1"
Range("Table1[#All]").Select
ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight9"
Range("Table1[[#Headers],[Column1]]").Select
ActiveCell.FormulaR1C1 = "Header1"
Range("Table1[[#Headers],[Column2]]").Select
ActiveCell.FormulaR1C1 = "Second Header"
Range("Table1[[#Headers],[Column3]]").Select
ActiveCell.FormulaR1C1 = "Third Header"
Range("Table1[[#Headers],[Column4]]").Select
ActiveCell.FormulaR1C1 = "Forth Header"
Range("Table1[[#Headers],[Column5]]").Select
ActiveCell.FormulaR1C1 = "Fifth Header"
Range("A2").Select
End Sub
Play a bit, see how it works, use F8. After some time, you can look for a way to avoid the .Select
and ActiveSheet
. This is some example that can be automized further with a loop, based on the number of the header rows. However, it does not use ActiveSheet
and Select
:
Option Explicit
Sub TestMe()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
Dim tbl As ListObject
With ws
.Cells.Clear
.ListObjects.Add(xlSrcRange, .Range("A1:E10"), , xlNo).Name = "MyFirstTable"
Set tbl = .ListObjects(1)
tbl.HeaderRowRange.Cells(1, 1) = "SomeHeader1"
tbl.HeaderRowRange.Cells(1, 2) = "SomeHeader2"
tbl.HeaderRowRange.Cells(1, 3) = "SomeHeader3"
tbl.HeaderRowRange.Cells(1, 4) = "SomeHeader4"
tbl.HeaderRowRange.Cells(1, 5) = "SomeHeader5"
End With
End Sub
E.g., if you want to loop through the header and hive some values, then this is the content of the With ws
:
With ws
.Cells.Clear
.ListObjects.Add(xlSrcRange, .Range("A1:E10"), , xlNo).Name = "MyFirstTable"
Set tbl = .ListObjects(1)
Dim myCell As Range
For Each myCell In tbl.HeaderRowRange.Cells
myCell = "SomeHeader " & myCell.Column
Next myCell
End With