Copy cells between workbooks

前端 未结 3 1954
广开言路
广开言路 2020-12-18 01:45

Could someone please help me with some VBA code.

I am trying to copy 2 ranges of cells between workbooks (both workbooks should be created beforehand as i don\'t wan

3条回答
  •  遥遥无期
    2020-12-18 02:00

    Here's an example of how to do one of the columns:

    Option Explicit
    Sub CopyCells()
        Dim wkbkorigin As Workbook
        Dim wkbkdestination As Workbook
        Dim originsheet As Worksheet
        Dim destsheet As Worksheet
        Dim lastrow As Integer
        Set wkbkorigin = Workbooks.Open("booka.xlsm")
        Set wkbkdestination = Workbooks.Open("bookb.xlsm")
        Set originsheet = wkbkorigin.Worksheets("Sheet3")
        Set destsheet = wkbkdestination.Worksheets("Sheet1")
        lastrow = originsheet.Range("H5").End(xlDown).Row
        originsheet.Range("H5:H" & lastrow).Copy  'I corrected the ranges, as I had the src
        destsheet.Range("B2:B" & (2 + lastrow)).PasteSpecial 'and destination ranges reversed
    End Sub
    

    As you have stated in the comments, this code above will not work for ranges with spaces, so substitute in the code below for the lastrow line:

    lastrow = originsheet.range("H65536").End(xlUp).Row
    

    Now ideally, you could make this into a subroutine that took in an origin workbook name, worksheet name/number, and range, as well as a destination workbook name, worksheet name/number, and range. Then you wouldn't have to repeat some of the code.

提交回复
热议问题