I don't have much experience with VBA so it's been difficult to troubleshoot this. When running the code, it outputs Array(i<=i)
instead of Array(i)
I've tested the for condition and found Array(0)
properly returns the result. However Array(1)
will print Array(1)
with Array(0)
and so on.
The goal of this code is to group worksheets based on their name and print them to pdfs based on grouping, i.e. all sheets starting with I1 to a single pdf.
Sub Test()
FolderPath = "C:\Example"
Dim aWS()
Dim n As Integer
Dim ws As Worksheet
Dim DocTypes()
DocTypes = Array("I1","I2","I3")
For i = LBound(DocTypes) To UBound(DocTypes)
For Each ws In Worksheets
If Left(ws.Name, 2) = DocTypes(i) Then
n = n + 1
ReDim Preserve aWS(1 To n) 'Add 1 to to array length
aWS(n) = ws.Name 'Add worksheet name meeting If condition
End If
Next ws
Sheets(aWS).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath &
DocTypes(i), _
openafterpublish:=True, ignoreprintareas:=False
Next i
End Sub
What I expect is:
i = 0 to 2
First Array(i) = "I1"
so output all sheets beginning with "I1" as a pdf
Then move to i = 1
Here Array(i) = "I2"
so output all sheets beginning with "I2" as a pdf
However when I step forward it doesn't seem to be following this logic and I don't understand why. I'm thinking it has to do with the selection, it would follow that if i=0
was selected, then i=1
was added to the selection this problem would make sense. I've tried re-selecting a single sheet right before Next i
to force past this but it didn't work. This leads me to think I've made a logical mistake in my for loops.