我正在尝试编写一些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
答案 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