0

I am trying to import a table from one workbook to another, but I want to add to the table with each import to the next empty cell (i.e. don't want to over-write existing data in the target workbook). I keep getting the Application-defined or object-defined error at the ' Paste values only into target sheet line.

Any suggestions? Thanks!

Sub Proforma()
    Dim sourceWB As Workbook
    Dim sourceWS As Worksheet
    Dim targetWB As Workbook
    Dim targetWS As Worksheet
    Dim filePath As String
    Dim sourceRange As Range
    Dim nextRow As Long
    Dim lastRow As Long, lastCol As Long
    
     ' Set reference to the original workbook
    Set targetWB = ThisWorkbook

    ' Set the path to the source workbook
    filePath = targetWB.Sheets("Load").Range("B3").Value
    
    ' Open the source workbook
    Set sourceWB = Workbooks.Open(filePath)
    Set sourceWS = sourceWB.Sheets("Proforma")
    
    ' Dynamically find the last used row and column in the source sheet
    lastRow = sourceWS.Cells(sourceWS.Rows.Count, "A").End(xlUp).Row
    lastCol = sourceWS.Cells(1, sourceWS.Columns.Count).End(xlToLeft).Column
    
    ' Define the source range of table
    Set sourceRange = sourceWS.Range(sourceWS.Cells(2, 1), sourceWS.Cells(lastRow, lastCol))
    
    ' Set the target worksheet
    Set targetWS = targetWB.Sheets("Wire ACH 2025")
    
    ' Find the next empty row in Column A of target sheet
    nextRow = targetWS.Cells(targetWS.Rows.Count, "A").End(xlUp).Row + 1
    
    ' Paste values only into target sheet
    targetWS.Cells(nextRow, 1).Resize(sourceRange.Rows.Count, sourceRange.Columns.Count).Value = sourceRange.Value
    
    ' Close source workbook without saving
    sourceWB.Close SaveChanges:=False
    
    DeleteRefErrors
    
    ' Success check...
    MsgBox "Table imported successfully!", vbInformation

End Sub
New contributor
Cailin Henry is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
2
  • 6
    Try adding Debug.Print "Values from " & sourceRange.Address & " being transferred to Row# " & nextRow just before the problem line, and check the output (in the VB editor Immediate pane) is what you expect. Are there any event handlers on the target sheet? Commented Nov 18 at 22:54
  • (In the VB Editor, press CTRL+G to get the Immediate Window) Commented Nov 19 at 0:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.