基于整数变量的VBA排序表

时间:2018-01-21 07:49:47

标签: excel vba excel-vba

我创建了Loop I,它应该计算A列中用ping背景着色的单元格数。如果单元格不是粉红色,那么我删除整行。每次这个循环执行时,大约有400行,循环非常慢。我想将我创建的循环更改为其他内容。

我只想检查从第二行到最后一行的行(在代码中为i到LR_Double),然后在列A中将所有行标记为“j”。之后,我想对行中的行进行排序一种方式,所有“j”行将是第一个并删除其他行。

另一个问题可能是根本没有粉红色背景的细胞。这是我的代码的相关部分:

Public tmpFile As Workbook
Public LR_Double As Long
Public i As Long
Public j As Long

LR_Double = .Cells(Rows.Count, "A").End(xlUp).Row
With tmpFile.Worksheets(2)
   ' i row number
   ' j duplicates number
        j = 0
    For i = LR_Double To 2 Step - 1
        If .Cells(i, "A").Interior.Color = 13551615 Then
            j = j + 1
        Else
           .Cells(i, "A").EntireRow.Delete
        End If
    Next i
End With

1 个答案:

答案 0 :(得分:1)

类似于(LR_DoubletempFile的虚拟值;以及局部变量而不是全局变量)。 icounter将初始化为0,但我想明确说明:

Public Sub test()

    Dim tmpFile As Workbook
    Dim LR_Double As Long
    Dim i As Long
    Dim counter As Long

    i = 0
    LR_Double = 6
    counter = 0

    Set tmpFile = ThisWorkbook

    Dim ws As Worksheet
    Set ws = tmpFile.Worksheets(2)

    With ws

        For i = 2 To LR_Double

            If .Cells(i, "A").Interior.Color = 13551615 Then
                .Cells(i, "A").Value = "j"
                counter = counter + 1
            Else
                .Cells(i, "A").Value = vbNullString
            End If

        Next i

        Dim sortRange As Range

        Set sortRange = ws.Range("A1:A" & LR_Double)

        SortData sortRange

        .Range("A" & 2 + counter & ":A" & LR_Double).EntireRow.Delete

    End With

End Sub

Private Sub SortData(ByVal sortRange As Range)

       sortRange.Sort key1:=sortRange.Cells(1, 1), _
      order1:=xlDescending, Header:=xlYes

End Sub