【发布时间】:2018-09-23 20:07:20
【问题描述】:
This script is used to filter column I data, copy it and move it to a new worksheet based on the first visible cell in I2 (header is I1). Afterwards, I would want to Loop it to go through the rest of the autofilter criteria without actually referencing anything, just running through the list. It seems to be working but it unselects all the data in Column I and doesn't name the sheet properly because the data results in blank rows. Can anyone help me?
我只需要代码即可:
按列 I(经理)自动筛选,选择所有单元格,创建新工作表,将过滤后的经理数据从原始数据粘贴到该新工作表中,根据 I 列中的第一个可见单元格值(经理名称)命名工作表,然后循环通过过滤器列表的其余部分,而不必引用经理名称,只是一个 Next 类型的循环功能,直到整个列表已经运行。
Sub Format()
Set My_Range = Worksheets("Sheet1").Range("A1:I" & LastRow(Worksheets("Sheet1")))
Set Name = FirstVisibleValue(ActiveSheet, 2, 9)
Cells.Select
Do
'Filter and set the filter field and the filter criteria :
My_Range.AutoFilter Field:=9, Criteria1:=ActiveCell.Value
'Add a new Worksheet
Set WSNew = Worksheets.Add(After:=Sheets("Sheet1"))
WSNew.Name = Name
'Copy/paste the visible data to the new worksheet
My_Range.Parent.AutoFilter.Range.Copy
With WSNew.Range("A1")
.PasteSpecial xlPasteValues
Cells.Select
End With
'Close AutoFilter
My_Range.Parent.AutoFilterMode = False
'Restore ScreenUpdating, Calculation, EnableEvents, ....
My_Range.Parent.Select
ActiveWindow.View = ViewMode
If Not WSNew Is Nothing Then WSNew.Select
With Application
.ScreenUpdating = True
.EnableEvents = True
.Calculation = CalcMode
End With
Loop
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
【问题讨论】:
-
这里有很多问题,我想说的第一是可读性 - 我会摆脱你添加的所有效率(所有
With Application位),你肯定不需要这些,因为你没有工作代码,而且它占用了你宏的一半以上。此外,您需要明确引用您的范围(Workbooks("Book1").Worksheets("Sheet1").Range("A1:I" & LastRow(Worksheets("Sheet1"))等。到处使用ActiveSheet和ActiveCell会搞砸你。 -
我刚刚编辑了代码,您能帮我识别 I2 中的第一个可见单元格以便正确命名工作表吗?