将单元格值从一个工作簿复制到另一个工作簿

时间:2012-09-26 18:44:21

标签: excel excel-vba vba

是excel的新手,并尝试将Cell E15的值从工作簿名称9月复制到另一个工作簿名称格式的D15,并且无法使用以下编码执行此操作。 请帮帮我

我使用以下编码来执行此操作。

Sub COPYCELL()
Dim wbk As Workbook
strFirstFile = "c:\documents and Settings\msivas\Desktop\James\September.xls"
strSecondFile = "c:\documents and Settings\msivas\Desktop\James\Format.xls"
Set wbk = Workbooks.Open(strFirstFile)
With wbk.Sheets("Summary")
Range("E15").Copy
End With
Set wbk = Workbooks.Open(strSecondFile)
With wbk.Sheets("sheet1")
Range("D12").PasteSpecial Paste:=xlPasteAll
End With
End Sub

收到错误但无法知道。

2 个答案:

答案 0 :(得分:3)

尝试此更新。通过不回收wbk变量,您将避免出现问题。

Sub COPYCELL()
Dim wbkOrg As Workbook, wbkDest as workbook
dim strFirstFile as string, strSecondFile as string

strFirstFile = "c:\documents and Settings\msivas\Desktop\James\September.xls"
strSecondFile = "c:\documents and Settings\msivas\Desktop\James\Format.xls"

Set wbkOrg = Workbooks.Open(strFirstFile)
Set wbkDest = Workbooks.Open(strSecondFile)

wbkOrg.Sheets("Summary").Range("E15").Copy wbkDest.Sheets("sheet1").Range("D12")

End Sub

答案 1 :(得分:0)

根据我的评论,这对我有用:

Option Explicit
Sub COPYCELL()
    Dim wbk1 As Workbook, wbk2 As Workbook
    Dim strFirstfile As String, strSecondFile As String

strFirstfile = "c:\documents and Settings\msivas\Desktop\James\September.xls"
strSecondFile = "c:\documents and Settings\msivas\Desktop\James\Format.xls"

    Set wbk1 = Workbooks.Open(strFirstfile)

    Set wbk2 = Workbooks.Open(strSecondFile)

    With wbk1.Sheets("Summary")
        .Range("E15").Copy
    End With

    With wbk2.Sheets("sheet1")
        .Range("D12").PasteSpecial Paste:=xlPasteAll
    End With
End Sub