如何找到最大索引并更改不同的活动工作表?

时间:2015-12-15 06:30:30

标签: excel

我怎么知道工作表中最大行的索引?我如何轻松地遍历不同的工作表?这是我编写的用于对工作表进行排序并为其分配排名的代码。我想让它从“1981”“1982”到“1995”的工作表循环。每个工作表的大小都不同。

Sub Macro3()


Cells(1, 11) = "ep_rank"
Cells(1, 12) = "bm_rank"
Cells(1, 13) = "combine_rank"

ActiveWorkbook.Worksheets("data1981").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("data1981").Sort.SortFields.Add Key:=Range( _
    "F2:F163"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
With ActiveWorkbook.Worksheets("data1981").Sort
    .SetRange Range("A1:J163")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
Dim i As Integer
For i = 1 To 200
    Cells(i + 1, 11) = i
Next i
End Sub

2 个答案:

答案 0 :(得分:0)

您应该能够遍历一系列数字,但将它们用作字符串,以便它们代表工作表.Name property,而不是Worksheets collection中工作表的数字索引。< / p>

Sub Macro3()
    dim w as long

    For w = 1982 To 1995
        With Worksheets("Data" & w)
            .Cells(1, 11).Resize(1, 3) = Array("ep_rank", "bm_rank", "combine_rank")
            With .Cells(1, 1).CurrentRegion
                With .Resize(.Rows.Count, 10)  '<~~only up to column J
                    'sort on column F ascending
                    .Cells.Sort Key1:=.Columns(6), Order1:=xlAscending, _
                                Orientation:=xlTopToBottom, Header:=xlYes
                End With
                With .Resize(.Rows.Count - 1, 1).Offset(1, 10) '<~~column K data
                    .Cells(1, 1) = 1  '<~~ K2
                    .DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, Step:=1
                End With
            End With
        End With
    Next w

End Sub

答案 1 :(得分:0)

这将负责循环遍历您的页面1982-1995以及最大行的索引。我在这里使用过Excel表格。因为,使用excel表并以这种方式访问​​它们要容易得多。

  Sub Macro3()

    Dim c as integer

    Cells(1, 11) = "ep_rank"
    Cells(1, 12) = "bm_rank"
    Cells(1, 13) = "combine_rank"

    For c =1981 to 1992 

    'Create an Excel table of the required range

    Sheet1Worksheets("data" & c & "").ListObjects.Add(xlSrcRange, Range("A1:J1").End(xlDown), , xlYes).Name = "Table" & c & ""

    ActiveWorkbook.Worksheets("data" & c & "").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("data" & c & "").Sort.SortFields.Add Key:= _
        Sheet1Worksheets("data" & c & "").listobjects("Table" & c & ""), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets("data" & c & "").Sort
        .SetRange Sheet1Worksheets("data" & c & "").ListObjects("Table" & c & "").databodyrange.select
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Dim i As Integer
    For i = 1 To 200
        Cells(i + 1, 11) = i
    Next i
    Next c

        End Sub