如果另一个工作表中不存在数据,则隐藏行

时间:2018-02-12 19:17:11

标签: excel vba excel-vba

我在工作表中有大约34,000行数据,我还需要隐藏另一个工作表中没有匹配数据的行。我有一些代码但我似乎隐藏所有数据而不是jst隐藏未在其他工作表中表示的数据。代码如下所示,任何帮助将不胜感激!

Sub HideCells()

Dim xlRange As Range
Dim xlCell As Range
Dim xlSheet As Worksheet, sht As Worksheet
Dim valueToFind
Dim i As Long, lastrow As Long, lastrow2 As Long

Set xlSheet = ActiveWorkbook.Worksheets("Køb VT nummer")
lastrow = xlSheet.Cells(xlSheet.Rows.Count, "A").End(xlUp).Row
Set xlRange = xlSheet.Range("A1:A" & lastrow)

Set sht = ActiveWorkbook.Worksheets("køb total")
lastrow2 = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

Debug.Print lastrow
Debug.Print lastrow2

For i = 2 To lastrow2

valueToFind = Sheets("køb total").Cells(i, 7).Value

For Each xlCell In xlRange
    If Not xlCell.Value = valueToFind Then
        Worksheets("Køb total").Rows(i).EntireRow.Hidden = True
        Exit For
    End If
Next xlCell

Next i

End Sub

2 个答案:

答案 0 :(得分:0)

这是因为对于“i”的一个值包含“ValueToFind”的行不一定包含不同的“i”值

尝试

Worksheets("Køb total").usedRange.rows.hidden = true

For i = 2 To lastrow2

    valueToFind = Sheets("køb total").Cells(i, 7).Value

    For Each xlCell In xlRange
        If xlCell.Value = valueToFind Then
            Worksheets("Køb total").Rows(i).EntireRow.Hidden = False
        End If
    Next xlCell

Next i

答案 1 :(得分:0)

如果在检查结束时完成所有隐藏,您的代码将运行得更快。

Sub HideCells()

    Dim xlRange As Range
    Dim xlCell As Range
    Dim xlSheet As Worksheet, sht As Worksheet
    Dim i As Long, lastrow As Long, lastrow2 As Long
    Dim rngHide As Range, c As Range

    Set xlSheet = ActiveWorkbook.Worksheets("Køb VT nummer")
    lastrow = xlSheet.Cells(xlSheet.Rows.Count, "A").End(xlUp).Row
    Set xlRange = xlSheet.Range("A1:A" & lastrow)

    Set sht = ActiveWorkbook.Worksheets("køb total")
    lastrow2 = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

    For Each c In sht.Range("G2:G" & lastrow2)

        'any match on the other sheet?
        If IsError(Application.Match(c.Value, xlRange, 0)) Then
            If rngHide Is Nothing Then
                Set rngHide = c
            Else
                Set rngHide = Application.Union(rngHide, c)
            End If
        End If

    Next c

    'any rows to hide?  If Yes then hide them all
    If Not rngHide Is Nothing Then rngHide.EntireRow.Hidden = True

End Sub