使细胞范围等于不同工作簿中的另一个细胞范围

时间:2016-03-30 14:49:41

标签: excel vba

我想从多个工作簿中获取一系列值,并将其输入到主工作簿的下一个空白行中。我正在尝试尽可能简化此代码,因为将有多个工作簿将输入到Masterwork书中的相应选项卡中。

示例:

Column C (MasterWorkbook,Sheet 2) = Column A (Workbook 1, Sheet 1)

问题:

  1. 如果行数每天都会改变,你能否将一系列单元格=另一个范围?
  2. 是否有一种简单的方法可以在代码中引用工作簿和工作表变量?例如: wk1.sht1.Origin.Value = wk2.sht2.Destination.Value
  3. 代码:

    Sub CopyData()
    
    
    Dim wk1 As Workbook
    Dim wk2 As Workbook
    Dim sht1 As Worksheet
    Dim sht2 As Worksheet
    Dim Origin As Range
    Dim Destination As Range
    
    Set wk1 = Workbooks("Device")
    Set wk2 = Workbooks("Pri Access Master)
    Set sht1 = Worksheets(1)
    Set sht2 = Worksheets("Device")
    
    Set Origin = Range("B2").End(xlDown)
    Set Destination = Range("D120000").End(xlUp).Offset(1, 0)
    
    '(Isn't working)Copy data in column B and paste in next blank row of another    workbook in another column
    wk2.sht2.Destination.Value = wk1.sht1.Origin.Value
    
    
    End Sub
    

1 个答案:

答案 0 :(得分:1)

您对对象的引用不正确 - 一旦设置了Range对象,您就不需要包含完整的“路径”:

Sub CopyData()


    Dim wk1 As Workbook
    Dim wk2 As Workbook
    Dim sht1 As Worksheet
    Dim sht2 As Worksheet
    Dim Origin As Range
    Dim Destination As Range

    Set wk1 = Workbooks("Device")
    Set wk2 = Workbooks("Pri Access Master")
    Set sht1 = wk1.Worksheets(1)
    Set sht2 = wk2.Worksheets("Device")
    Set Destination = sht2.Range("D120000").End(xlUp).Offset(1, 0)

    'EDIT - dynamic copy range
    Set Origin = sht1.Range(sht1.Range("B2"), sht1.Cells(sht1.Rows.Count, "B").End(xlUp))



    Destination.Resize(Origin.Rows.Count, Origin.Columns.Count).Value = _
                                                           Origin.Value
End Sub