0

I want to copy values from one excel file to another excel file, but on later stages of my project, I may need to cross check the value and then paste it in the new excel file. So I dont want to copy whole sheet at a time. I want to copy a value by value.

I was able to open and switch between to excel file but I m not able to copy and paste the values. Following is the code I tried-

Private Sub CommandButton1_Click()
Dim x As Long
Dim NumRows As Long
Set fromwb = Workbooks.Open("G:\Excel\From.xlsx")
Set towb = Workbooks.Open("G:\Excel\To.xlsx")
fromwb.Activate
NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count
ReDim a(1 To NumRows)

For x = 1 To NumRows
    fromwb.Activate
    a(x) = Cells(x, 1).Value

    towb.Activate
    Cells(x, 1).Value = a(x)
Next x

End Sub

Thanking you in anticipation.

Nitin Jadhav
  • 497
  • 1
  • 7
  • 17

2 Answers2

0

You just need to specify the to cells as equal to the from cells, no need to loop anything.

Workbooks("To.xlsx").Sheets("ToSheetNameHere").Range("rangehere").Value = Workbooks("From.xlsx").Sheets("FromSheetNameHere").Range("rangehere").Value

Keep in mind if you have macro code in the workbook(s) they will be .xlsm and not .xlsx

Gamah
  • 29
  • 1
  • 1
  • 6
0

Try out the code below. I hope the comments are very clear!

Option Explicit
Private Sub CommandButton1_Click()

Dim SourceBook As Workbook, DestBook As Workbook
Dim SourceSheet As Worksheet, DestSheet As Worksheet
Dim Index As Long, NumRows As Long
Dim ValidCheck As Boolean

'set references up-front
Set SourceBook = Workbooks.Open("G:\Excel\From.xlsx")
Set SourceSheet = SourceBook.ActiveSheet
With SourceSheet
    NumRows = .Range("A", .Rows.Count).End(xlUp).Row '<~ last row in col A
End With
Set DestBook = Workbooks.Open("G:\Excel\To.xlsx")
Set DestSheet = DestBook.ActiveSheet

'loop through col A and write out values to destination
For Index = 1 To NumRows

    '...
    'do your value validation
    'in this space using ValidCheck
    '...

    If ValidCheck Then '<~ if true write to Dest
        DestSheet.Cells(Index, 1) = SourceSheet.Cells(Index, 1)
    End If '<~ if not, do not write to Dest

Next Index

End Sub
Dan Wagner
  • 2,693
  • 2
  • 13
  • 18
  • The method for determining the number of rows to iterate through used above is pretty-well vetted and recommended by the VBA wizards here on S.O. I keep this post bookmarked in case I ever need a quick review: http://stackoverflow.com/questions/11169445/error-finding-last-used-cell-in-vba – Dan Wagner May 16 '14 at 16:28