【发布时间】:2012-04-01 08:23:12
【问题描述】:
我有一本工作簿,我们在其中进行报价成本计算。有一个名为“成本核算表”的主表和可以具有不同名称的各个表。所有工作表都具有相同的格式,第一行作为标题。我只想要一个宏,它将在“成本核算表”中的 A 列中搜索一个值,并与其他工作表的 A 列中的值进行比较,如果找到,则复制整行 A:W 从带有公式和格式的单个工作表到“成本核算”表”对匹配值。我创建了一个宏,它复制所有数据并创建一个新工作表。但这并没有给我想要的输出。我搜索了几个论坛,但找不到相同的。如果你能帮助我,那将是很大的帮助这是我用于创建新工作表的代码
Sub CopyFromWorksheets()
Dim wrk As Workbook
Dim sht As Worksheet
Dim trg As Worksheet
Dim rng As Range
Dim colCount As Integer
Set wrk = ActiveWorkbook
For Each sht In wrk.Worksheets
If sht.Name = "Master" Then
MsgBox "There is a worksheet called as 'Master'." & vbCrLf & _
"Please remove or rename this worksheet since 'Master' would be" & _
"the name of the result worksheet of this process.", vbOKOnly + vbExclamation, "Error"
Exit Sub
End If
Next sht
Application.ScreenUpdating = False
Set trg = wrk.Worksheets.Add(After:=wrk.Worksheets(wrk.Worksheets.Count))
'Rename the new worksheet
trg.Name = "Master"
'Get column headers from the first worksheet
'Column count first
Set sht = wrk.Worksheets(1)
colCount = sht.Cells(1, 255).End(xlToLeft).Column
'Now retrieve headers, no copy&paste needed
With trg.Cells(1, 1).Resize(1, colCount)
.Value = sht.Cells(1, 1).Resize(1, colCount).Value
'Set font as bold
.Font.Bold = True
End With
'We can start loop
For Each sht In wrk.Worksheets
'If worksheet in loop is the last one, stop execution (it is Master worksheet)
If sht.Index = wrk.Worksheets.Count Then
Exit For
End If
'Data range in worksheet - starts from second row as first rows are the header rows in all worksheets
Set rng = sht.Range(sht.Cells(2, 1), sht.Cells(65536, 1).End(xlUp).Resize(, colCount))
'Put data into the Master worksheet
trg.Cells(65536, 1).End(xlUp).Offset(1).Resize(rng.Rows.Count, rng.Columns.Count).Value = rng.Formula
Next sht
'Fit the columns in Master worksheet
trg.Columns.AutoFit
Sheets("Master").Select
colCount = Range("A" & Rows.Count).End(xlUp).Row
Range("L2:L" & colCount).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
'Screen updating should be activated
Application.ScreenUpdating = True
Sheets("Costing Sheet").Select
End Sub
【问题讨论】: