VBA“恢复到计算列公式”

时间:2018-04-19 21:18:26

标签: excel vba excel-vba

我有一个我差不多完成的程序,它根据Number,ID和Date(new-old)对excel表进行排序,然后在Number列中删除没有我想要的任何特定数字的行,然后将公式放在新列中以查找每个新ID的第一个匹配项。当我运行它时,整个最后一列显示“1”并且左上角有一个绿色三角形,如果我点击它,我可以选择“恢复到计算列公式”。当我点击它时,它按照我想要的方式编号,除了它从第3行开始,这会弄乱所有数字。我认为问题与删除行有关。如何使用VBA解决此问题(必须自动化)? 我的代码:

'sorting
Dim tName As String
With ActiveSheet.ListObjects(1).Sort
    tName = .Parent.Name 'list name

    .SortFields.Clear
    .SortFields.Add Key:=Range(tName & "[Number]"), SortOn:=xlSortOnValues, _
        Order:=xlAscending, DataOption:=xlSortNormal
    .SortFields.Add Key:=Range(tName & "[ID]"), SortOn:=xlSortOnValues, _
        Order:=xlAscending, DataOption:=xlSortTextAsNumbers
    .SortFields.Add Key:=Range(tName & "[Date]"), SortOn:=xlSortOnValues, _
        Order:=xlDescending, DataOption:=xlSortNormal

    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

'deletes all rows that arent the right #
Dim firstrow As Long
Dim lastrow As Long
With Sheets(1)
    firstrow = 2
    With ActiveSheet
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With
    For Lrow = lastrow To firstrow Step -1
        With .Cells(Lrow, "A")
            If Not IsError(.Value) Then
                If .Value <> "407" And .Value <> "412" And .Value <> "416" And .Value <> "419" And .Value <> "445" And .Value <> "434" And .Value <> "441" And .Value <> "4100" And .Value <> "440" And .Value <> "486" And .Value <> "428" And .Value <> "417" Then
                    .EntireRow.Delete
                End If
            End If
        End With
    Next Lrow
End With

'restore to calculated column formula?
'puts formula in last column to find newest
Dim targetRow As Long
With ActiveSheet
    lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row 'new lastrow bc deleted
End With
Dim cell As Range
targetRow = 2
Sheets(1).Range("AJ" & 1).Value = "Selection"
Columns("AJ:AJ").Select
Selection.NumberFormat = "General" 'formatting bc previous column is text

For Each cell In Sheets(1).Range("A1:A" & lastrow)
    Sheets(1).Range("AJ" & targetRow).Value = "=COUNTIF($D$2:D2,D2)"
    targetRow = targetRow + 1
Next cell

0 个答案:

没有答案