如何循环浏览除TOC以外的工作表

问题描述 投票:0回答:1

我正在尝试循环一个将贯穿所有工作表的宏,但“ TOC”表除外。-每个工作表都将创建,格式化表格并放入公式。

但是,宏尝试从“ TOC”表开始,然后导致错误。

我目前有:

Sub BrandRank_()

Dim wb As ThisWorkbook
Dim ws As Worksheet
Dim TableName As String
Dim LstObj As ListObjects
Dim LastRow As Long

For Each ws In ThisWorkbook.Worksheets
Select Case ws.Name
Case Is = "TOC"

Case Else
With ws

‘Insert Table
TableName = "MyTable"
Range("A3").CurrentRegion.Select
ActiveSheet.ListObjects.Add(xlSrcRange, Selection.CurrentRegion, , xlYes).Name = TableName

'Apply a filter to $ Share for all Brands (Largest to Smallest)
ws.AutoFilter.Sort.SortFields.Clear
ws.AutoFilter.Sort.SortFields.Add2 Key:=Range("C3"), SortOn:=xlSortOnValues, Order:=xlDescending
ws.AutoFilter.ApplyFilter
ActiveSheet.ListObjects("Table1").ShowAutoFilterDropDown = False

'More Table Formatting Code

End With
End Select
Next ws


End Sub
excel vba
1个回答
0
投票

如注释中所指出,您没有使用With ws语句。我也在本月早些时候在another one of your questions中看到了此问题,所以我想就如何正确使用该语句提供一个解释。

考虑此代码:

Sub WithStatementExample()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")

With ws
    Range("A1").Value = "This cell is A1 and this sheet name is " & ws.Name
    ActiveSheet.Range("A2").Value = "This cell is A2 and this sheet name is " & ws.Name
End With

End Sub 

现在,尽管我们的语句被封装在With语句中,但是在执行代码时,单元格A1A2的输出实际上都将位于活动工作表上。

例如,考虑这本新的工作簿,该工作簿有3张纸,都带有默认名称:

New workbook with 3 blank sheets

[如果我们基于该屏幕快照中的工作簿执行代码,则结果将到达我们假设它们将达到的位置-Sheet1单元格A1A2。但是,如果我们在Sheet3处于活动状态时运行代码,则代码会将值输出到Sheet3单元格A1A2

Example output of code with Sheet3 selected

这是因为在With语句中,我们没有将ws工作表用作Range属性的对象限定符。

range属性可以同时应用于ApplicationWorksheet对象以及每个Application.Range documentation

[当不使用对象限定符使用时,此属性是ActiveSheet.Range的快捷方式(它返回活动工作表中的范围;如果活动工作表不是工作表,则该属性失败)。

要使用objectWith块中获取语句,请在语句前面键入.

Sub WithStatementExample()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")

With ws
    .Range("A1").Value = "This cell is A1 and this sheet name is " & ws.Name
    .Range("A2").Value = "This cell is A2 and this sheet name is " & ws.Name
End With

End Sub 

现在输出将仅到达分配给ws变量的工作表-在这种情况下为Sheet1

Gif showing all from sheet3 to sheet1, demonstrating where the output is

如果需要将某些语句应用于other工作表但要在With块中执行,最好使用对工作簿的显式引用,而不要使用ActiveSheet-This will help explain more - (How to avoid using select in vba)

因此,如果您代码中的ListObjects实际上位于Sheets("TOC") not whichever wsthe loop is referring to, I'd changeActiveSheet.ListObjects ...andActiveSheet.ListObjects(“ Table1”)...`上:

wb.Sheets("TOC").ListObjects...
wb.Sheets("TOC").ListObjects("Table1")...
© www.soinside.com 2019 - 2024. All rights reserved.