我的VBA宏工作在文件的一个副本上,但不在主副本上

时间:2017-04-11 19:37:51

标签: excel vba excel-vba

我保存了一份数据表副本以处理我的宏。我终于让宏在这个副本上没有错误地工作但是当我在主数据集上运行它时会出错。

宏基本上计算然后排序2列数据。然后运行此计数并对工作簿中的所有10多个工作表进行排序。当我在主数据集上运行它时会出现错误91'在第3或第4张之后。

这部分代码在第一次编写时是一个问题,但是我修复了它并运行它没有问题复制数据集"。这一切都在我的计算机上完成,文件保存到桌面。

'    turn the sheet name into a generic name
    Dim WS As Worksheet
    Dim WB As Workbook
    Dim LR As Integer

    Set WB = ThisWorkbook

    For Each WS In WB.Worksheets
      With WS
        .Activate

' When sheet is blank skip to the next one
        If .Range("A3").Value = vbNullString Then GoTo NextWS:

' Sets the variable for commands down the entire set of data
        LR = WS.Range("A" & Rows.count).End(xlUp).Row

' Insert new column
        Columns("E:E").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

' Add title of "Qty Used" to new column
        .Range("E2").FormulaR1C1 = "Qty Used"

' count how many times each tool shows up
        .Range("E3").FormulaR1C1 = "=COUNTIF(R3C4:R65536C4,RC[-1])"

'For sheets with one row it will skip the low to high sort
        If LR > 3 Then

' run the count command down the list
        .Range("E3").AutoFill Destination:=Range("E3:E" & LR)
        End If

' puts autofilter range
        If .Range("A2:AK2").AutoFilter = True Then
        .Range("A2:AK2").AutoFilter
        End If

        .Range("A2:AK2").AutoFilter
' Calculate worksheet so it can sort properly
        .Calculate

' clears old filters
        .AutoFilter.Sort.SortFields.Clear

' filters based on low to high for Qty Used column
        .AutoFilter.Sort.SortFields.Add Key:= _
            Range("E2"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
            xlSortNormal
        With .AutoFilter.Sort
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With

' sorts tools for unique numbers
        Columns("D:D").AdvancedFilter Action:=xlFilterInPlace, Unique:=True

' process the next worksheet
      End With
NextWS:
    Next WS

    Set WB = Nothing
    Set WS = Nothing

0 个答案:

没有答案