VBA工作表循环

时间:2014-11-13 04:36:10

标签: vba loops excel-vba excel

我有24张名为0到23的纸张,需要在下面为每张纸张循环命令。 我已经尝试了一些循环过程,因为我在许多教程中找到但没有一个是有效的,需要你的建议

Sheets("0").Select
Cells.Select
Range("B1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents

最近我尝试了这段代码,但它停在" Sheets(i)。选择" 运行时错误' 9': 下标超出范围

Dim i as integer
  For i = 0 To 23
   Sheets(i).Select
   Cells.Select
   Range("B1").Select
   Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
   Selection.Clear
 Next i   

3 个答案:

答案 0 :(得分:0)

如果我正确地阅读您的问题,您问的是如何遍历工作簿中的工作表并执行您显示的代码,对吗?如果是这样,请参阅此Microsoft支持文章:

http://support.microsoft.com/kb/142126

答案 1 :(得分:0)

阅读其他答案和相关评论我的理解是,您希望遍历工作簿中的所有工作表并清除除A列之外的任何内容。您可以这样做:

        Sub AllButA()

        Dim ws As Worksheet


        For Each ws In ThisWorkbook.Worksheets '<~~ it will loop over the worksheets in the workbook
            For i = ws.UsedRange.Columns.Count To 2 Step -1 '<~~ we go from the last used column in the sheet to column 2 (column B) from high to low to avoid messing with the indexes
                ws.Columns(i).ClearContents '<~~ we clear the column content
            Next
        Next


        End Sub

如果你想坚持使用明确命名的工作表,你可以这样做:

        Sub AllButA()

        Dim ws As Worksheet


        For i = 0 To 23
            Set ws = ThisWorkbook.Worksheets(CStr(i)) '<~~ instead of looping we assign the worksheet variable by name
            For j = ws.UsedRange.Columns.Count To 2 Step -1 '<~~ same as the other example, just with j instead of i
                ws.Columns(j).ClearContents
            Next
        Next


        End Sub

如果后者符合您的需求,请检查表格名称为Fumu 7建议

答案 2 :(得分:-1)

用于清除除“A”列以外的单元格的VBA代码将是

Range("B1").Select  'select top left corner of range to be cleared.
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select  'select upto bottom right corner(xlLastCell) of range to be cleared.
Selection.Clear 'Clear selected cells.

要申请名为“0”,“1”.....,“23”的工作表,请在上面的代码之外添加工作表的循环。这可能会成为:

Dim i as integer, sheetname as string
Dim ws as Worksheet

For i=0 to 23
  sheetname=Cstr(i)   'create sheetname from number (loop variable i)
  set ws = worksheets(sheetname)    
  ws.Activate 'select worksheet with name  "0","1",... and "23" for each
  Range("B1").Select  'select top left corner of range to be cleared.
  Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select  'select upto bottom right corner(xlLastCell) of range to be cleared.
  Selection.Clear 'Clear selected cells.
next i