VBA-EXCEL-与其他工作簿同时复制不同的范围/单元格

时间:2015-07-28 05:23:23

标签: excel vba excel-vba

我无法弄清楚如何在不使用.activate的情况下在不同的工作簿之间复制单元格值(即使是合并的单元格)。我知道如何避免选择:     dim x作为范围     昏暗的wrk1作为工作簿     昏暗的wrk2作为工作簿     dim w作为范围     dim作为范围     dim e as range'等......

但我不能在不使用.activate的情况下复制范围。 我喜欢得到像以下一样的东西:

sub avoid()

dim x as range
dim wrk1 as workbook
dim wrk2 as workbook
dim w as range
dim r as range 
dim e as range
set wrk1 = application.workbook("cartel1")   'already open workbook 
set wrk2 = workbook.open("workB")            'workbook was closed
set x = wrk1.range("a1")
set e = wrk1.range("a3")
set w = wrk2.range("a1")
set r = wrk2.range("a2")
x.copy(w)
e.copy(r)
end sub

但它不起作用。 有帮助吗? 感谢

2 个答案:

答案 0 :(得分:0)

删除括号:

x.copy w
e.copy r

或者只是复制值:

w.Value = x.Value 
r.Value = e.Value

答案 1 :(得分:0)

你犯了很多错误。所以,我修改了它。我已经测试了代码。它对我很有用。试试这个:

Public Sub avoid()

    Dim source1 As Range
    Dim source2 As Range

    Dim dest1 As Range
    Dim dest2 As Range

    Dim sourceBook As Workbook
    Dim destBook As Workbook

    Set sourceBook = Application.Workbooks("cartel1")

    'Here you need to set full path of new work book
    'Because new work book is same level with source work book, so I set => ThisWorkbook.Path & "\" & "workB"
    'Open destination work book

    Workbooks.Open Filename:=ThisWorkbook.Path & "\" & "workB"

    Set destBook = Application.Workbooks("workB")

    'Here, we can't get a Range from a workbook.
    'Only, we can get it from a worksheet. You forget to get sheet. I do it. Check.
    'You need to modify sheet names.

    Set source1 = sourceBook.Sheets("sourceSheet").Range("A1")
    Set source2 = sourceBook.Sheets("sourceSheet").Range("A3")

    Set dest1 = destBook.Sheets("destSheet").Range("A1")
    Set dest2 = destBook.Sheets("destSheet").Range("A2")

    source1.Copy dest1
    source2.Copy dest2

End Sub