从工作簿复制范围(无文件夹路径版本)



我最近一直在寻找加快将数据从一个工作表复制到另一个工作表的方法。我遇到了这段不错的代码(但是这是在 2013 年发布的)。

你能帮忙吗?我不想指定工作簿的任何路径(如下例所示)。我打开了两个工作表,并希望通过文件名解决它们。

我尝试将"工作簿.打开"更改为"窗口("xxx").激活",但这不起作用。

谢谢!

Sub foo()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")

x.Sheets("name of copying sheet").Range("A1").Copy
y.Sheets("sheetname").Range("A1").PasteSpecial

结束子

Sub foo()
    Dim x As Workbook
    Dim y As Workbook
    'Replace the text between the "" with the exact name of the workbook
    Set x = Workbooks("ActualNameOfWorkBook.xls")
    Set y = Workbooks("ActualNameOfOtherWorkBook.xls")

    x.Sheets("name of copying sheet").Range("A1").Copy
    y.Sheets("sheetname").Range("A1").PasteSpecial
End Sub

使用 PasteSpecial 时,您需要添加XlPasteTypewhat(您要使用的复制范围内的参数)。XlPasteTypewhat的一些选项是:xlPasteAllxlPasteFormulasxlPasteValues等。

您可以在 MSDN 上阅读有关它的更多信息。

在下面的示例中,我使用的是 xlPasteAll .

法典

Sub foo()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open("file_name_x.xslx") '<-- don;t forget to add the extension, .xslx or .xlsm
Set y = Workbooks.Open("file_name_y.xslx") '<-- don;t forget to add the extension, .xslx or .xlsm
x.Sheets("name of copying sheet").Range("A1").Copy
y.Sheets("sheetname").Range("A1").PasteSpecial xlPasteAll '<-- add parameter after the PasteSpecial 
End Sub

最新更新