views:

748

answers:

2

I've got an Excel 2007 Spreadsheet and I'd like to write a VBA procedure to print particular worksheets by name. How do I do this?

For example, I'd like to print "FirstSheet","ThirdSheet", and "FourthSheet" but not "SecondSheet".

A: 

Something similar to the following should work:

Dim sh As Worksheet
For Each sh In ActiveWorkbook.Worksheets
        If (sh.Name = "Sheet1") Then
           sh.PrintOut
        End If
Next sh
Jon
Can this be done in a batch? e.g. Can I print multiple sheets out in a single print job?
Caveatrob
+1  A: 
Public Sub PrintByName(Names As Variant)

  Dim s As Worksheet
  Dim i As Integer

  If IsArray(Names) Then
    For Each s In ActiveWorkbook.Worksheets
      For i = 0 To UBound(Names)
        If StrComp(s.Name, Names(i), vbTextCompare) = 0 Then
          s.PrintOut
        End If
      Next i
    Next s
  End If

End Sub

Call like:

PrintByName Array("FirstSheet", "ThirdSheet", "FourthSheet")

The nested loop is not optimal, in regards to runtime performance. With the limited number of sheets an Excel workbook can contain, I think this is negligible. However, using a Collection to contain the desired sheet names instead of an Array would be better.

Tomalak
Do you think accusing *and* insulting people the same time is helpful in any way?
Tomalak
Sorry if I offended your fragile ego.
Jon
I don't think that it's my ego that is being fragile here.
Tomalak