[英]VBA Code: How to Copy Rows & Create Sheets based on column data From MS Excel
这将为column B
唯一数据创建一个新工作表,并将工作表重命名为单元格值。 您可能必须修改代码以适合您的目的。
Sub dave()
Dim dicKey, dicValues, data, lastrow As Long
Dim i As Long, ws As Worksheet, wsDest As Worksheet
Set ws = ActiveSheet
lastrow = Cells(Rows.count, 2).End(xlUp).Row
data = Range("B2:B" & lastrow) ' load data into variable
With CreateObject("scripting.dictionary")
For i = 1 To UBound(data)
If .Exists(data(i, 1)) = False Then
dicKey = data(i, 1) 'set the key
dicValues = data(i, 1) 'set the value for data to be stored
.Add dicKey, dicValues
Set wsDest = Sheets.Add(After:=Sheets(Worksheets.count))
wsDest.Name = data(i, 1)
Sheets(data(i, 1)).Cells(1, 1).Value = ws.Cells(i + 1, 2).Value
End If
Next i
End With
End Sub
尝试这个:
Option Explicit
Sub main()
Dim cell As Range, dataRng As Range
With Worksheets("Offices").UsedRange '<--| change "Offices" with your actual sheet name
Set dataRng = .Cells
With .Offset(, .Columns.Count).Resize(, 1)
.Value = .Parent.Columns("B").Value
.RemoveDuplicates Columns:=Array(1), Header:=xlYes
With .SpecialCells(XlCellType.xlCellTypeConstants)
For Each cell In .Offset(1).Resize(.Rows.Count - 1)
AddSheet cell.Value
With dataRng
.AutoFilter field:=2, Criteria1:=cell.Value
.SpecialCells(xlCellTypeVisible).Copy Destination:=Worksheets(cell.Value).Cells(1, 1)
End With
Next cell
End With
.Parent.AutoFilterMode = False
.Clear
End With
End With
End Sub
Sub AddSheet(shtName As String)
Dim ws As Worksheet
On Error Resume Next
Set ws = Worksheets(shtName)
On Error GoTo 0
If ws Is Nothing Then Worksheets.Add.Name = shtName
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.