将VBA用于包装订单:
我试图隐藏不同表格中的行,这些表格与第一张表格中已过滤(因此隐藏)的行具有相同的serial_nr。
因为不同工作表上的行不一样,所以我尝试使用serial_nr。但我似乎无法将serial_nr值链接为选择要隐藏在其他工作表中的行的条件。
最后,我将其分解为最简单的代码,我可以毫无错误地获得但不起作用。
Sub Filter_over_multiple_sheets()
Dim Serial_nr As Integer
Dim Row_nr As Integer
For Row_nr = 3 To 1020
If Worksheets("Raaplijst").Cells(Row_nr, 1).EntireRow.Hidden = True Then
Worksheets("Boutenlijst Kist B").Cells(Row_nr, 1).EntireRow.Hidden = True
End If
Next
End Sub
我仍然是VBA的新手,所以我迷失在可能的所有方法和组合中。
你们中的任何人都可以提供帮助吗?
答案 0 :(得分:1)
尝试此代码,您必须为项目添加“Microsoft Scripting Runtime”引用才能利用Dictionary
类
Option Explicit
Sub Filter_over_multiple_sheets()
Dim IDsDict As New Dictionary
Dim rng As Range
With Worksheets("Raaplijst") '<--| consider "mother" worksheet
For Each rng In .Range("A3", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants) '<--| loop through column "A" non empty cells from row 3 down to last non empty one
If rng.EntireRow.Hidden Then If Not IDsDict.Exists(CStr(rng.Value)) Then IDsDict.Add CStr(rng.Value), rng.Value '<--| if row is hidden add its ID to dictionary provided it's not been added already
Next rng
End With
If IDsDict.Count > 0 Then '<--| go on if there's been at least one hidden row ID
With Worksheets("Boutenlijst Kist B") '<--| consider "child" worksheet
With .Range("A2", .Cells(.Rows.Count, 1).End(xlUp)) '<--| loop through column "A" cells fom row 2 (header) down to last non empty one
.AutoFilter field:=1, Criteria1:=(IDsDict.Keys), Operator:=xlFilterValues '<--| filter column "A" with IDs corresponding with "mother" worksheet hidden rows
If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then '<--| if any cell has been filtered...
Set rng = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) '<--| ... store filtered cells in a range variable...
.AutoFilter '<--| .. show all rows back...
rng.EntireRow.Hidden = True '<--| ... and hide only just stored cells rows
Else '<--| otherwise
.AutoFilter '<--| .. show all rows back...
End If
End With
End With
End If
End Sub
答案 1 :(得分:0)
据我所知,你有最好的使用方法,它是最简单的。只是一些事情,你的Serial_nr变量没有被使用,它可能最好修复你的if语句上的缩进,它使得阅读更容易,特别是在长段代码中,最后使用.Rows而不是.Cells
Sub Filter_over_multiple_sheets()
Dim Row_nr As Integer
For Row_nr = 3 To 1020
If Worksheets("Sheet1").Rows(Row_nr).EntireRow.Hidden = True Then
Worksheets("Sheet2").Rows(Row_nr).EntireRow.Hidden = True
End If
Next
End Sub