Excel工作表:将数据从一个工作簿复制到另一个工作簿

时间:2016-06-21 03:50:37

标签: excel vba excel-vba copy

我无法将数据从一个工作簿复制到另一个工作簿。但是在同一个工作簿中它的工作。运行宏程序后,目标工作表为空。我有2个代码。两者都不起作用。我的源文件是 .xlsx 格式,目标文件是 .xlsm 格式。有什么错误吗?

代码1:

Sub mycode()

Workbooks.Open Filename:="source_file"
Worksheets("Sheet1").Cells.Select
Selection.Copy


Workbooks.Open Filename:="destination_file"
Worksheets("Sheet1").Cells.Select
Selection.PasteSpecial
ActiveWorkbook.Save


End Sub

代码2

Sub foo2()
Dim x As Workbook
Dim y As Workbook

Set x = Workbooks.Open("source file")
Set y = Workbooks.Open("destination file")

y.Sheets("Sheet1").Range("A1").Value = x.Sheets("Sheet1").Range("A1")

x.Close

End Sub

2 个答案:

答案 0 :(得分:1)

我假设你在一个单独的文件中写下 Code1 Code2 excel宏,比如说copy_paste.xlsm

当您向Workbooks.open提供完整的文件路径时,

代码1 正在运行:

Sub mycode()

Workbooks.Open Filename:="C:\Users\xyz\Documents\Excel-Problem\source_file.xlsx"
Worksheets("Sheet1").Cells.Select
Selection.Copy

Workbooks.Open Filename:="C:\Users\xyz\Documents\Excel-Problem\destination_file.xlsm"
Worksheets("Sheet1").Cells.Select
Selection.PasteSpecial xlPasteValues               'xlPasteAll to paste everything
ActiveWorkbook.Save

ActiveWorkbook.Close SaveChanges:=True             'to close the file
Workbooks("source_file").Close SaveChanges:=False  'to close the file

End Sub

要粘贴所有内容(公式+值+格式),请将粘贴类型用作xlPasteAll

代码2 也在运作,您只需要提供完整路径,而文件名中缺少_

Sub foo2()
Dim x As Workbook
Dim y As Workbook

Set x = Workbooks.Open("C:\Users\xyz\Documents\Excel-Problem\source_file.xlsx")
Set y = Workbooks.Open("C:\Users\xyz\Documents\Excel-Problem\destination_file.xlsm")

'it copies only Range("A1") i.e. single cell
y.Sheets("Sheet1").Range("A1").Value = x.Sheets("Sheet1").Range("A1")

x.Close SaveChanges:=False
y.Close SaveChanges:=True

End Sub

答案 1 :(得分:1)

已修改以添加(最小)文件检查

您必须指定完整的文件路径,名称和扩展名

此外,您只能打开目标文件,例如

Option Explicit

Sub foo2()
    Dim y As Workbook
    Dim sourcePath As String, sourceFile As String, destFullPath As String '<--| not necessary, but useful not to clutter statements

    sourcePath = "C:\Users\xyz\Documents\Excel-Problem\" '<--| specify your source file path down to the last backslash and with no source file name
    sourceFile = "source_file.xlsx" '<--| specify your source file name only, with its extension
    destFullPath = "C:\Users\xyz\Documents\Excel-Problem\destination_file.xlsm" '<--| specify your destination file FULL path

    If Dir(destFullPath) = "" Then '<--| check is such a file actually exists
        MsgBox "File " & vbCrLf & vbCrLf & destFullPath & vbCrLf & vbCrLf & "is not there!" & vbCrLf & vbCrLf & vbCrLf & "The macro stops!", vbCritical
    Else
        Set y = Workbooks.Open(destFullPath)

        With y.Sheets("Sheet1").Range("A1")
            .Formula = "='" & sourcePath & "[" & sourceFile & "]Sheet1'!$A$1"
            .Value = .Value
        End With

        y.Close SaveChanges:=True
    End If
End Sub

您甚至可以使用Excel4macro

打开它们