The following code refers to a given worksheet through its name, written as a text in column A:A
in Worksheets("Overview")
:
Sub PrintWorksheetNames()
Dim myCell As Range
Dim lastCell As Long
lastCell = LastRow("Overview")
For Each myCell In ThisWorkbook.Worksheets("Overview").Range("A1:A" & lastCell).Cells
Dim wksName As String
wksName = myCell.Text
ThisWorkbook.Worksheets(wksName).Range("A1:C20").PrintOut Copies:=1, Collate:=True
Next
End Sub
Public Function LastRow(wsName As String, Optional columnToCheck As Long = 1) As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(wsName)
LastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row
End Function
Public Function LastRow(wsName As String, Optional columnToCheck As Long = 1) As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(wsName)
LastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row
End Function
- The range, in which the names of the worksheets are written is defined by
ThisWorkbook.Worksheets("Overview").Range("A1:A" & lastCell).Cells
.
- The abovementioned range could be hardcoded, if it is not going to be changed -
ThisWorkbook.Worksheets("Overview").Range("A1:A8").Cells
. Thus the additional function LastRow()
is not needed.
lastCell
is the result of LastRow()
for column A
. A
is the first column, thus the optional parameter takes care of it.
- How to avoid using Select in Excel VBA (This is a must-read for every VBA person)