我无法将数据透视表格式粘贴到另一个页面

时间:2019-08-21 16:22:57

标签: vba format pivot-table copy-paste

尝试将Excel数据透视表从一页复制并粘贴到另一页。 代码可以使用,但不能粘贴格式。

Sub TestPivotPaste()
Dim wb As Workbook
Dim sh As Worksheet
Dim sh1 As Worksheet
Dim copyrange As Range

Set wb = ActiveWorkbook
Set sh = wb.Worksheets(8)
Set copyrange = sh.Range("A1:Z50")
Set sh1 = wb.Worksheets(9)


copyrange.Copy
sh1.Range("B50").PasteSpecial Paste:=xlPasteValues
sh1.Range("B50").PasteSpecial Paste:=xlPasteFormats
sh1.Range("B50").PasteSpecial Paste:=xlPasteColumnWidths

End Sub

我试图在同一页面上完成

Sub TestPivotPaste()
Dim wb As Workbook
Dim sh As Worksheet
Dim copyrange As Range
Set wb = ActiveWorkbook
Set sh = wb.Worksheets(8)
Set copyrange = sh.Range("A1:Z50")
copyrange.Copy
sh.Range("B50").PasteSpecial Paste:=xlPasteValues
sh.Range("B50").PasteSpecial Paste:=xlPasteFormats
sh.Range("B50").PasteSpecial Paste:=xlPasteColumnWidths
End Sub

它仍然被复制而没有格式,我得到 运行时错误1004:Range类的PasteSpecial方法失败并且有罪的行是

sh.Range("B50").PasteSpecial Paste:=xlPasteFormats

我无法通过在本网站上找到类似的答案来弄清楚问题出在哪里

1 个答案:

答案 0 :(得分:0)

尝试如下复制整个表格范围(您可能需要更改数据透视表所属的范围):

Sub TestPivotPaste()

Dim wb As Workbook
Dim sh As Worksheet
Dim sh1 As Worksheet
Dim copyrange As Range

Set wb = ActiveWorkbook
Set sh = wb.Worksheets(8)
Set pt = sh.Range("A3").PivotTable
Set sh1 = wb.Worksheets(9)
Set copyrange = pt.TableRange1

copyrange.Copy
sh1.Range("B50").PasteSpecial Paste:=xlPasteValues
sh1.Range("B50").PasteSpecial Paste:=xlPasteFormats
sh1.Range("B50").PasteSpecial Paste:=xlPasteColumnWidths

End Sub