首页 > 解决方案 > 复制和合并列值

问题描述

我有一个用于从数据透视表中复制/粘贴值并将它们输出到另一个工作表中的代码。一切都很好,但我希望将数据透视表中的前两列组合起来,然后输出到它们自己的列中。我不确定我将如何开始

在此处输入图像描述

Sub InsertData()

Dim wsCopy As Worksheet, wsDest As Worksheet
Dim DefCopyLastRow As Long, DefDestLastRow As Long


'Set variables for copy and destination sheets
Set wsCopy = Workbooks("Warranty Template.xlsm").Worksheets("PivotTable")
Set wsDest = Workbooks("QA Matrix template.xlsm").Worksheets("Plant Sheet")

'1. Find last used row in the copy range based on data in column A
DefCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, 1).End(xlUp).Offset(-1, 0).Row



'2. Find first blank row in the destination range based on data in column D
'Offset property moves down 1 row
DefDestLastRow = wsDest.Cells(wsDest.Rows.Count, 10).End(xlUp).Offset(1, 0).Row



'3. Copy & Paste Data For Each Filter Selection

'Backhoes
With ActiveWorkbook.SlicerCaches("Slicer_Model_Family_Description")
        .SlicerItems("Backhoes Case Burlington").Selected = True
        .SlicerItems("CE Tractor Loader Burlington").Selected = False
        .SlicerItems("Corn Headers Burlington").Selected = False
        .SlicerItems("Dozer Case Calhoun Burlington").Selected = False
        .SlicerItems("Draper & Pickup Headers Burlington").Selected = False
        .SlicerItems("Forklift Case Burlington").Selected = False
        .SlicerItems("Grain Headers Burlington").Selected = False
        If .SlicerItems("Backhoes Case Burlington").Selected Then

'1. Find last used row in the copy range based on data in column A
DefCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, 1).End(xlUp).Offset(-1, 0).Row



'2. Find first blank row in the destination range based on data in column D
'Offset property moves down 1 row
DefDestLastRow = wsDest.Cells(wsDest.Rows.Count, 10).End(xlUp).Offset(1, 0).Row

'3. Copy and Paste Data
[INSERT COLUMN A & B COMBINED OUTPUTTED TO COLUMN D]

wsCopy.Range("D5:D" & DefCopyLastRow).Copy
wsDest.Range("P" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues

wsCopy.Range("E5:E" & DefCopyLastRow).Copy
wsDest.Range("S" & DefDestLastRow).PasteSpecial Paste:=xlPasteValues

NewLastRow = wsDest.Cells(wsDest.Rows.Count, 10).End(xlUp).Row
wsDest.Range("AG" & DefDestLastRow & ":AG" & NewLastRow).Value = "Final Customer"

wsDest.Range("D" & DefDestLastRow & ":D" & NewLastRow).Value = "TLB"


End If
End With
End Sub

标签: excelvba

解决方案


你可以这样做:

Dim r

r = wsCopy.Evaluate("=A5:A" & DefCopyLastRow & " & B5:B" & DefCopyLastRow)
wsDest.Range("D" & DefDestLastRow).Resize(UBound(r, 1), 1).Value = r

Evaluate(在这种情况下)将生成一个二维数组(1 到 #rows,1 到 #cols)


推荐阅读