VBA Copy/Paste from different workbooks

SE123654

New Member
Joined
Jul 1, 2024
Messages
2
Office Version
  1. 365
Platform
  1. Windows
I am trying to Copy from 1 workbook (S.xls) and pasting into (PD.xlsm). However I also get the same error 1004- Application-defined or object-defined error at this line "lastCol = sh1.Cells(1, Columns.Count).End(xlToLeft).Column"

VBA Code:
Sub Rectangle1_Click()
  Dim sh1 As Worksheet, sh2 As Worksheet
  Dim wb1 As Workbook, wb2 As Workbook
  Dim j As Long, lr1 As Long, lr2 As Long
  Dim f As Range
  Application.ScreenUpdating = False
 
  Set wb1 = Workbooks("S.xls")
  Set sh1 = wb1.Sheets(1) 'origin
  Set wb2 = Workbooks("PD.xlsm")
  Set sh2 = wb2.Sheets("PD")  'destination
 
  'last row on origin sheet
  lr1 = sh1.Cells.Find("*", , xlValues, , xlByRows, xlPrevious).Row
  'last row on destination sheet
  lr2 = sh2.Cells.Find("*", , xlValues, , xlByRows, xlPrevious).Row + 1
 
  'for each head in sh1 (origin)
  lastCol = sh1.Cells(1, Columns.Count).End(xlToLeft).Column
   For j = 1 To lastCol
    Set f = sh2.Rows(1).Find(sh1.Cells(1, j), , xlValues, xlWhole, , , False)
    If Not f Is Nothing Then
     sh2.Cells(lr2, f.Column).Resize(lr1).Value = sh1.Cells(2, j).Resize(lr1).Value
    End If
  Next
 
  wb1.Close False
 
  Application.ScreenUpdating = True
 
  MsgBox "End"

End Sub



Also there there a way to edit this so that it puts the number in a 11 digit format 100xxxxxxxx?
 
Last edited by a moderator:

Excel Facts

Save Often
If you start asking yourself if now is a good time to save your Excel workbook, the answer is Yes
Seems like it should be....
VBA Code:
Dim lasrCol as Long
lastCol = sh1.Cells(1, sh1.Columns.Count).End(xlToLeft).Column
The "Format" function should be useful. HTH. Dave
 
Upvote 0

Forum statistics

Threads
1,223,880
Messages
6,175,157
Members
452,615
Latest member
bogeys2birdies

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top