在另一个工作表中搜索值并隐藏行(如果工作表中不存在该行)

时间:2018-02-12 16:04:13

标签: excel vba excel-vba

我正在尝试编写一些VBA代码来检查一个工作表中的数字与另一个工作表中的数字。我试图让excel隐藏一个工作表中的行,如果它不存在于另一个工作表中。我已经编写了一些代码,但我似乎无法使其正常运行,任何建议都将受到赞赏。 VBA代码附在下面。

Sub HideCells()

Dim xlRange As Range
Dim xlCell As Range
Dim xlSheet As Worksheet
Dim valueToFind
Dim i As Long


For i = 2 To Rows.Count

valueToFind = Sheets("køb total").Cells(i, 1).Value
Set xlSheet = ActiveWorkbook.Worksheets("Køb VT nummer")
Set xlRange = xlSheet.Range("A1:A50000")

For Each xlCell In xlRange
    If xlCell.Value = valueToFind Then

        Else
        Worksheets("Køb total").Rows("i").EntireRow.Hidden = True

    End If
Next xlCell
Next i

End Sub

2 个答案:

答案 0 :(得分:1)

情侣更改 - 删除了i语句中If周围的引号,将一些Set移到了循环之外,并将If/Else语句更改为一个案例If Not

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, 1).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

虽然我认为您仍需要将Rows.Count替换为lastrow,但您应该确保它与您的想法相同(通过使用F8单步执行代码,将光标移到{{} 1}}并看到它的价值是什么。)

答案 1 :(得分:1)

试试这个:

Sub HideCells()

Dim xlRange As Range
Dim xlCell As Range
Dim xlSheet As Worksheet
Dim valueToFind
Dim i As Long
Dim bExists As Boolean


For i = 2 To Rows.Count

    valueToFind = Sheets("køb total").Cells(i, 1).Value
    Set xlSheet = ActiveWorkbook.Worksheets("Køb VT nummer")
    Set xlRange = xlSheet.Range("A1:A50000")

    For Each xlCell In xlRange

        If xlCell.Value = valueToFind Then

            bExists = True
            Exit For
        End If
    Next xlCell

    If Not bExists Then
        Worksheets("Køb total").Rows("i").EntireRow.Hidden = True
    End If
Next i

End Sub