我正在尝试将过滤器应用于文件夹中的多个工作簿。我的代码中的循环可以打开给定文件夹中的所有.xlsm
文件,但是我无法将循环应用于过滤器。我需要将相同的过滤器应用于所有工作簿。
我希望我真的很明白,这只是我在这里缺少的简单东西。
第一个较长的宏会打开给定文件夹中的所有.xlsm
文件,但只会自动过滤活动的工作簿,而不是所有打开的工作簿。第二个宏是我试图简化宏的尝试,但是没有成功,除了打开了文件对话框并且可以选择文件夹之外,但此后什么也没有发生。没有打开文件或未过滤文件。
在那个宏上,我得到
运行时错误438:对象不支持此属性或方法
在.autofilter field:=1....
Sub Main()
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Application.ScreenUpdating = False
On Error Resume Next
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
xFile = Dir(xStrPath & "\*.xlsm")
Do While xFile <> ""
Workbooks.Open xStrPath & "\" & xFile
xFile = Dir
Loop
'Filter_Rows_By_RSSID
For Each xWB In Application.Workbooks
With Worksheets("Sheet1").Range("A1")
.AutoFilter field:=1, Criteria1:=Array("5649", "15899", "16583", "27314", "27471", "32551", "33111", "33124", "34404", "34607", "35157", "35331", "35546", "57203", "57450", "57803", "58119", "58413"), Operator:=xlFilterValues
End With
Next
End Sub
Sub BadLoopThroughFiles()
Dim xFd As FileDialog
Dim xFdItem As Variant
Dim xFileName As String
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
If xFd.Show = -1 Then
xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
xFileName = Dir(xFdItem & "*.xls*")
Do While xFileName <> ""
With Workbooks.Open(xFdItem & xFileName)
.AutoFilter field:=1, Criteria1:=Array("5649", "15899", "16583", "27314", "27471", "32551", "33111", "33124", "34404", "34607", "35157", "35331", "35546", "57203", "57450", "57803", "58119", "58413"), Operator:=xlFilterValues
End With
xFileName = Dir
Loop
End If
End Sub
答案 0 :(得分:0)
您的With
块
With Workbooks.Open(xFdItem & xFileName)
.AutoFilter field:=1, Criteria1:=Array("5649", "15899", "16583", "27314", "27471", "32551", "33111", "33124", "34404", "34607", "35157", "35331", "35546", "57203", "57450", "57803", "58119", "58413"), Operator:=xlFilterValues
End With
将导致此错误,因为您既没有指定工作表,也没有为自动过滤器指定范围。
您可以设置一个变量=要打开的工作簿,并引用工作表和范围以进行自动过滤。然后,您可以删除With
块,因为您只是在使用它。
Dim wb as Workbook
Set wb = Workbooks.Open(xFdItem & xFileName)
wb.Worksheets(1).Range("A1").AutoFilter field:=1, Criteria1:=Array("5649", "15899", "16583", "27314", "27471", "32551", "33111", "33124", "34404", "34607", "35157", "35331", "35546", "57203", "57450", "57803", "58119", "58413"), Operator:=xlFilterValues