I just wanna ask about how the loop workflow and why does my code doesn't work.
Basically I need to loop to create a Pivot Data Table from each worksheet in a workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
For i = 1 To WS_Count
lastRow = Range("IB" & Rows.Count).End(xlUp).Row
ActiveCell.FormulaR1C1 = "=IF(AND(RC[-1]<=2,RC[-1]>=0),""Ok"",""Failed"")"
Range("ID2").Select
Selection.AutoFill Destination:=Range("ID2:ID" & lastRow)
If i Mod 2 = 0 Then
SrcData = ActiveSheet.Name & "!" & Range("A1:IF" & lastRow) _
.Address(ReferenceStyle:=xlR1C1)
Set sht = Sheets.Add
StartPvt = sht.Name & "!" & sht.Range("A1:C3") _
.Address(ReferenceStyle:=x1R1C1)
Set pvtCache = ActiveWorkbook.PivotCaches _
.Create(SourceType:=xlDatabase, SourceData:=SrcData)
Set pvt = pvtCache.CreatePivotTable(TableDestination:=StartPvt, _
TableName:="PivotTable1")
End if
Next i
What is happening to my code is that this loop assigns everything that I wanted to assign using that formula, but the for the IF
part it always runs the code. So after the third loop, it will give an error message said that pivot talbe source is undefined because the Activesheet is empty and no data in it.
What I need is, is my code right? Or, how do I make the IF
statement work only if it's correct?