我是 VBA 的新手,我在使用嵌入式 if 陳述句時遇到了問題。我想要做的是讓我的回圈,遍歷我的陣列以獲得 CC 號碼和這些 CC 號碼的組名。我的代碼應該做的是過濾主源檔案,過濾 CC 編號,為這些 CC 編號創建新作業表,然后為這些新的組作業表創建一個帶有資料透視表的新作業表。
到目前為止,我的代碼是成功的,除了原始檔案中不會出現 CC 編號的情況,我希望它洗掉新的 ws 并轉到下一個 CC 編號,然后再執行以下創建新作業表的步驟、資料透視表等。希望這是有道理的。
我的錯誤是在這一行:
If dataRG Is Nothing Then subWS.delete
將不勝感激任何幫助。
'Loop through array for sheet names
For n = UBound(wsNames) To LBound(wsNames) Step -1
Set subWS = wb.Worksheets.Add(After:=ws)
'rename ws using sheet names array
subWS.Name = wsNames(n)
If IsArray(ccNumbers(n)) Then 'multiple group numbers in array
dataRG.AutoFilter 7, ccNumbers(n), xlFilterValues
Else
dataRG.AutoFilter 7, ccNumbers(n) 'x;And' is default (irrelevant)
End If
If dataRG Is Nothing Then subWS.delete
End If
Set dfCell = subWS.Range("A1")
'copy column widths
dataRG.Rows(1).Copy
dfCell.PasteSpecial xlPasteColumnWidths
'select first cell as selection is first row by product of 'PasteSpecial
dfCell.Select
'copy visible cells only
dataRG.SpecialCells(xlCellTypeVisible).Copy dfCell
'set range for subws
Set subRG = subWS.Range("A1").CurrentRegion
'Format each sheet as a table
subWS.ListObjects.Add(SourceType:=xlSrcRange, Source:=subRG).Name = TbleNames(n)
'Add new WS for pivots
Set pvtWS = Sheets.Add(After:=subWS)
pvtWS.Name = PvtNames(n)
'Define Pivot Caches
Set subCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=subRG)
'Create Pivot Tables
Set subPvtTable = subCache.CreatePivotTable(TableDestination:=pvtWS.Cells(1, 1), TableName:="1")
Next n
uj5u.com熱心網友回復:
在您的代碼中,您正在測驗是否dataRG是Nothing,但是當您測驗它應該已經是某種東西時,因為您剛剛在dataRG范圍內執行了一些代碼(在If...else宣告中ccNumbers)
您的代碼的處理部分似乎完全取決于dataRG不是Nothing. 我認為這是確定您的自動過濾器是否已回傳結果。
那么為什么不將代碼的整個設定部分封裝在一個If基于回傳結果的陳述句中呢?
像下面,例如
'Loop through array for sheet names
For n = UBound(wsNames) To LBound(wsNames) Step -1
If IsArray(ccNumbers(n)) Then 'multiple group numbers in array
dataRG.AutoFilter 7, ccNumbers(n), xlFilterValues
Else
dataRG.AutoFilter 7, ccNumbers(n) 'x;And' is default (irrelevant)
End If
Set rg = ws.AutoFilter.Range.SpecialCells(xlCellTypeVisible)
'If Not dataRG Is Nothing Then
If rg.Rows.Count > 1 Then 'please note that if your table doesn't have headers you should use 0 i.s.o. 1 here
Set subWS = wb.Worksheets.Add(After:=ws)
Set subRG = subWS.Range("A1").CurrentRegion
Set pvtWS = Sheets.Add(After:=subWS)
Set dfCell = subWS.Range("A1")
rg.Rows(1).Copy
dfCell.PasteSpecial xlPasteColumnWidths
rg.Copy dfCell
subWS.Name = wsNames(n)
subWS.ListObjects.Add(SourceType:=xlSrcRange, Source:=subRG).Name = TbleNames(n)
pvtWS.Name = PvtNames(n)
Set subCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=subRG)
Set subPvtTable = subCache.CreatePivotTable(TableDestination:=pvtWS.Cells(1, 1), TableName:="1")
End If
Next n
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/537932.html
標籤:擅长VBAif语句
