我正在尝试根据单元格A3中的名称列将工作表1中的数据拆分为多个工作表。我面临的问题是,如果两者之间存在差距,我无法追踪数据。例如,名称从A3到A100开始,在A10,A20和A20之间。 A30为空,程序只会追踪从A3到A9的值。对我来说另一个问题是指定标题。我想要使用的标题从单元格A2,B2,C2和...开始。 D2和该程序将标题显示为A1,B1,C1& D1,因为该单元格中有值。这是我的代码。
Private Sub CommandButton1_Click()
Dim ws As Worksheet, Rng As Range, cc
Dim temp As Worksheet, CostC As Range, u
Set ws = Sheets("Sheet1") 'where your original data. adjust to suit
Set Rng = ws.Range("a1").CurrentRegion.Resize(, 15)
Set CostC = ws.Range("a3", ws.Range("a" & Rows.Count).End(xlUp))
u = UNIQUE(CostC)
Application.ScreenUpdating = 0
For Each cc In u
With Rng
.AutoFilter field:=1, Criteria1:="=" & cc
On Error Resume Next
Set temp = Sheets(cc)
On Error GoTo 0
If Not temp Is Nothing Then
DoThis:
.SpecialCells(xlCellTypeVisible).Copy temp.Range("A1")
Else
Set temp = Sheets.Add
temp.Name = cc
GoTo DoThis
End If
.AutoFilter
End With
Set temp = Nothing
Next
Application.ScreenUpdating = 1
End Sub
Function UNIQUE(r As Range)
Dim a, v
If IsArray(r.Value) Then
a = r.Value
With CreateObject("scripting.dictionary")
.comparemode = vbTextCompare
For Each v In a
If Not IsEmpty(v) Then
If Not .exists(v) Then .Add v, Nothing
End If
Next
If .Count > 0 Then UNIQUE = .keys
End With
Erase a
Else
UNIQUE = r.Value
End If
End Function
答案 0 :(得分:0)
这是一个稍微不那么优化但更简单的版本:
Private Sub CommandButton1_Click()
Dim ws As Worksheet, c As Range
Dim temp As Worksheet, CostC As Range, u
Set ws = Sheets("Sheet1")
Set CostC = ws.Range(ws.Range("A3"), ws.Range("A" & Rows.Count).End(xlUp))
For each c in CostC.Cells
u = trim(c.Value)
If len(u) > 0 then
Set temp = Nothing '<<EDIT
On Error Resume Next
Set temp = Sheets(u)
On Error GoTo 0
If temp is Nothing then
Set temp = Sheets.Add()
ws.Range("A2").Resize(1, 15).Copy temp.range("a1") 'copy headers
temp.Name = u
End If
c.resize(1, 15).copy temp.cells(rows.count,1).end(xlup).offset(1,0)
End if 'have name
Next c
End Sub
答案 1 :(得分:0)
使用ColumnDifferences
方法返回范围,然后使用该范围的Areas(1)
属性将数据复制到新工作表中,然后您可以删除数据并重复,或循环遍历区域并复制它们。