简体   繁体   中英

VBA - Copying worksheet from one workbook to another (values, not formulas)

Currently, I am copying the values and formats of a worksheet to a worksheet in another workbook as such:

workbooks("book1.xlsm").sheets(1).range(someRange).copy
with workbooks("book2.xlsm").sheets(1).range("A1")
    .pasteSpecial xlPasteValues
    .pasteSpecial xlPasteFormats
end with

I would like to use something like:

workbooks("book1.xlsm").sheet(1).copy after:=workbooks("book2.xlsm").sheet(1)

The problem is that some of the cells in sheet(1) of book1.xlsm have formulas. Using the second method pulls the formulas, and the resulting values are linked to the data in book2.xlsm

How can I use the second method, but have the values, not formulas, copied?

If not possible, what are some alternatives, aside from the first method, which I am currently using?

You can break the links after the copy operation:

Option Explicit

Sub copySheetValues()

    With Workbooks("Book2")

        Workbooks("Book1").Worksheets(1).Copy After:=.Worksheets(1)

        Application.Wait Now + TimeValue("0:00:01") 'built-in replacement for "Sleep"

        .BreakLink Name:=Workbooks("Book1.xlsm").FullName, Type:=xlLinkTypeExcelLinks

    End With

End Sub

Note: both files need to be open in the same instance of the Excel application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM