tags:

views:

19

answers:

2

I'm trying to create a macro that selects most of the sheets in the workbook and then uses ExportAsFixedFormat to print them to PDF.

The problem is, while I know the sheets I don't want to include, I don't know exactly which sheets will be in place in at given time, so I can't make a static list of "Select these sheets" (It'd probably be painful to maintain anyway).

Is there some way to, say, "Select all then unselect these specific sheets" or something similar?

A: 

There isn't. Which doesn't prevent you from doing it yourself:

Public Sub SelectExceptThese(ByVal wb As Workbook, ExceptThese() As String)

  Dim ws() As String
  ReDim ws(1 To wb.Worksheets.Count)

  Dim wt As Worksheet
  Dim i As Long
  For Each wt In wb.Worksheets
    If Not IsInArray(ExceptThese, wt.Name) Then
      i = i + 1
      ws(i) = wt.Name
    End If
  Next

  If i > 0 Then
    ReDim Preserve ws(LBound(ws) To LBound(ws) + i - 1)
    wb.Worksheets(ws).Select
  End If

End Sub

Private Function IsInArray(arr() As String, val As String) As Boolean
  Dim i As Long

  For i = LBound(arr) To UBound(arr)
    If arr(i) = val Then
      IsInArray = True
      Exit Function
    End If
  Next
End Function
GSerg
+1  A: 

How about:

Dim s As Worksheet
DoNotInclude = "Sheet2"
For Each s In ActiveWorkbook.Worksheets
    If InStr(DoNotInclude, s.Name) = 0 Then
        ''Do something
    End If
Next
Remou
The problem here is in the `''Do something` part. Yes, you can go `.Select False` to have the current sheet be added to the currently selected sheets, but try to accomodate this to a situation when an unwanted sheet is already the active sheet. This code then will include it into the selection.
GSerg