我正在研究一个简单的子例程,以从主工作表中提取值并将这些值移动到其他工作表中。当我运行 VBA 宏时,它永远不会超过子例程声明,任何建议都将不胜感激。
Option Explicit
Sub Macro2()
Dim rCell As Range, ws As Worksheet
Application.DisplayAlerts = False
With Sheets("Sheet1")
Sheets.Add().Name = "Temp"
.Range("D2", .Range("D" & Rows.Count).End(xlUp)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("Temp").Range("B1"), Unique:=True
For Each rCell In Sheets("Temp").Range("D2", Sheets("Temp").Range("B" & Rows.Count).End(xlUp))
If Not IsEmpty(rCell) Then
.Range("D2").AutoFilter field:=3, Criteria1:=rCell
If SheetExists(rCell.Text) Then
Set ws = Sheets(rCell.Text)
Else
Set ws = Worksheet.Add(After:=Worksheets(Worksheets.Count - 1))
ws.Name = rCell
End If
With .AutoFilter.Range
.Offset(1).Resize(.Rows.Count - 1).Copy ws.Range("A" & Rows.Count).End(xlUp)(2)
End With
End If
Next rCell
Sheets("Temp").Delete
.AutoFilterMode = False
End With
Application.DisplayAlerts = True
End Sub
新增功能
Function SheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
SheetExists = Not sht Is Nothing
End Function
新错误
extract range has a illegal or missing field name
@
.Range("D2", .Range("D"&Rows.Count).End(xlDown)).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Sheets("Temp").Range("B1"), Unique:=True