我有2本工作簿。工作簿1和工作簿2.我正在从工作簿2中对工作簿1进行排序和筛选。
Sub filter_5PKT1_rows()
Dim file_name As String
Dim sheet_name As String
file_name = "C:\Users\Desktop\pocket setter excel\workbook 1.xlsm"
Dim wb As Workbook, mysh As Worksheet
Set wb = Application.Workbooks.Open(file_name)
Set mysh = wb.Sheets(1)
Dim My_Range As Range
Dim CalcMode As Long
Dim ViewMode As Long
Set My_Range = Range("A1:L" & LastRow(wb.ActiveSheet))
My_Range.Parent.Select
If ActiveWorkbook.ProtectStructure = True Or _
My_Range.Parent.ProtectContents = True Then
MsgBox "Sorry, not working when the workbook or worksheet is protected", _
vbOKOnly, "Copy to new worksheet"
Exit Sub
End If
'Change ScreenUpdating, Calculation, EnableEvents, ....
With Application
CalcMode = .Calculation
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableEvents = False
End With
ViewMode = ActiveWindow.View
ActiveWindow.View = xlNormalView
wb.ActiveSheet.DisplayPageBreaks = False
My_Range.Parent.AutoFilterMode = False
My_Range.AutoFilter Field:=4, Criteria1:=Array("5PKT Men's", "5PKT Women's", "5PKT Short"), Operator:=xlFilterValues
My_Range.AutoFilter Field:=1, Criteria1:=Array("Band 10", "Band 13", "Band 17", "Band 19"), Operator:=xlFilterValues
Range("J1") = "PSD"
Columns("A:L").sort key1:=Range("J2"), _
order1:=xlAscending, Header:=xlYes
My_Range.Parent.Select
ActiveWindow.View = ViewMode
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
End Sub
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlValues, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
当工作簿1中的列标题不变时,这非常有效。
工作簿1将每周更新并通过电子邮件发送给我。发生此更新时,会添加新列或列位置可能会更改。
如果发生这种情况,我怎么能执行我的排序和过滤,因为我不能通过列/字段编号来引用。
例如AutoFilter Field:= 4,
此实例中的字段4是具有名称产品类型的列标题 下次更新此工作簿时,它可能会更改为其他内容
有没有办法找到特定的列标题,可能使用Like语句,并执行排序和过滤?
答案 0 :(得分:0)
Dim col As Integer
col = 1
Do Until Range("A1").offset(0, col - 1).Value = "targetColumnHeader"
col = col + 1
' if the column name changed or is misspelled,
' want to loop forever, put a limit:
If col > 200 Then
Exit Do
End If
Loop
然后使用该col值:
... Field:=col, ...
这可能是一种更清晰的方式来编写循环。这只是我的第一个想法。
答案 1 :(得分:0)
您可以使用Find()查找标题:
Dim f as Range, hdr As String
hdr = "*product*type*" 'can use wildcards here....
Set f = ActiveSheet.Rows(1).Find(what:=hdr, lookat:=xlWhole)
If Not f Is Nothing Then
My_Range.AutoFilter Field:=f.Column, Criteria1:=Array("5PKT Men's", _
"5PKT Women's", "5PKT Short"), _
Operator:=xlFilterValues
Else
MsgBox "Couldn't find header ' & hdr & ' !", vbExclamation
Exit Sub
End If