【发布时间】:2019-06-03 12:37:07
【问题描述】:
我一直在编写一个工作簿,以根据数据透视表中的值创建和填充工作表。
我使用与此类似的方法根据列表创建工作表(归功于 ccm.net 上的 rizvisa1):
Sub CreateSheetsFromAList()
Dim nameSource As String 'sheet name where to read names
Dim nameColumn As String 'column where the names are located
Dim nameStartRow As Long 'row from where name starts
Dim detailSheet As String 'sales detail sheet name
Dim detailRange As String 'range to copy from sales detail sheet
Dim nameEndRow As Long 'row where name ends
Dim employeeName As String 'employee name
Dim newSheet As Worksheet
nameSource = "Pivot"
nameColumn = "A"
nameStartRow = 5
detailSheet = "Pivot"
'this is the range where I want to only copy and paste the rows/records that match the new sheet name
detailRange = "A5:D463"
'find the last cell in use
nameEndRow = Sheets(nameSource).Cells(Rows.Count, nameColumn).End(xlUp).Row
'loop till last row
Do While (nameStartRow <= nameEndRow)
'get the name
employeeName = Sheets(nameSource).Cells(nameStartRow, nameColumn)
'remove any white space
employeeName = Trim(employeeName)
' if name is not equal to ""
If (employeeName <> vbNullString) Then
On Error Resume Next 'do not throw error
Err.Clear 'clear any existing error
'if sheet name is not present this will cause error to leverage
Sheets(employeeName).Name = employeeName
If (Err.Number > 0) Then
'sheet was not there, so it create error, so we can create this sheet
Err.Clear
On Error GoTo -1 'disable exception so to reuse in loop
'add new sheet
Set newSheet = Sheets.Add(After:=Sheets(Sheets.Count))
'rename sheet
newSheet.Name = employeeName
Application.CutCopyMode = False 'clear clipboard
'copy sales detail
Sheets(detailSheet).Range(detailRange).Copy
'paste training material
Sheets(employeeName).Cells(1, "A").PasteSpecial
Application.CutCopyMode = False
End If
End If
nameStartRow = nameStartRow + 1 'increment row
Loop
End Sub
我只复制了一个静态范围。
我的问题是选择第一列与工作表名称匹配的范围,以便复制并粘贴到新创建的工作表中。我尝试使用For Each,其中一个单元格与工作表名称匹配并复制整行。
这就是我想要做的:
然后将其转换为具有 A 列工作表名称的新工作表,仅填充与工作表名称匹配的数据,如下所示:
【问题讨论】: