简体   繁体   中英

Issue with VBA - Copying from one workbook to another?

I'll preface this by saying I'm a complete novice to VBA but not coding. I'm trying to write part of a VBA script that can copy data from one worksheet in another workbook to a pre-existing worksheet in another workbook.

I'm trying to make use of dynamic ranges as I know the starting point for the data every time however my issues comes when it comes to the copying. The code runs up to the point of the copy where it stagnates with no error codes. Effectively gets stuck in stasis requiring user action.

Set sht = ThisWorkbook.Worksheets("Requisitions Raised")
Set StartCell = ThisWorkbook.Worksheets("Requisitions Raised").Range("A8")
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
Set startingRange = sht.Range(StartCell, sht.Cells(LastRow, LastColumn))

Set sht = Workbooks(FileName).Worksheets("1-Data")
Set StartCell = Workbooks(FileName).Worksheets("1-Data").Range("A8")
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
Set copyRange = sht.Range(StartCell, sht.Cells(LastRow, LastColumn))

ThisWorkbook.Worksheets("Requisitions Raised").startingRange.Value = Workbooks(FileName).Worksheets("1-Data").copyRange.Value

I've also tried the below to no avail

Workbooks(FileName).Worksheets("1-Data").copyRange.Copy Destination:=ThisWorkbook.Worksheets("Requisitions Raised").startingRange

What's causing the error? Is there a better copying solution?

Cheers!

As per my comment, you currently Set your Range object, but then try to use them as members of the Worksheet , which would (at least for me) result into a compile error.

Instead of copy/paste, I would advise a dynamic Value transfer. As per @FoxfireAndBurnsAndBurns also said; you need equal sized Range object (or arrays). So therefor I included a Resize of Range("A8") . Try the following:

Dim sht1 As Worksheet, sht2 As Worksheet
Dim lr As Long, lc As Long

Set sht1 = ThisWorkbook.Worksheets("Requisitions Raised")
Set sht2 = Workbooks(FileName).Worksheets("1-Data")

lr = sht2.Cells(sht2.Rows.Count, 1).End(xlUp).Row
lc = sht2.Cells(8, sht2.Columns.Count).End(xlToLeft).Column

sht1.Cells(8, 1).Resize(lr - 7, lc).Value = sht2.Range(sht2.Cells(8, 1), sht2.Cells(lr, lc)).Value

As you can see I used also two different variables for Worksheet . Not per se really meaningfull names, but it helps to distinquish. I guess it's a personal preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM