1

I need to copy data from a workbook to another, but anytime i tried to run my macro a get the runtime error "438" on the line containing the "select" operation. Thanks to all , and sorry if i've made noob errors but i'm relatively new to vba :)

here's my code:

Private Sub FileChoose_Click()
Dim fd As FileDialog
Dim FileName As String
Dim wb1 As Workbook
Set wb1 = ActiveWorkbook
Dim wb2 As Workbook 
Set fd = Application.FileDialog(msoFileDialogOpen) 
Dim filechosen As Integer
filechosen = fd.Show
fd.Title = "Scegliere il file da confrontare"
fd.InitialView = msoFileDialogViewSmallIcons
fd.Filters.Clear
fd.Filters.Add "Excel File", "*.xlsx"
fd.Filters.Add "Excel File con Macro", "*.xlsm"
fd.FilterIndex = 1
fd.ButtonName = "Apri"
If filechosen <> -1 Then
MsgBox "Nessun File Selezionato"
Else
FileName = fd.SelectedItems(1)
Set wb2 = Workbooks.Open(FileName)
Call Insert(wb2, wb1)
End If
End Sub


Private Sub Insert(wb2 As Workbook, wb1 As Workbook)
Dim myrange As Range
Set myrange = Range("B2:GT22")
For i = 1 To 24
wb2.Worksheets(i).Activate
wb2.ActiveSheet.myrange.Select <--- there is the error 
Selection.Copy 
wb1.Worksheets(i + 1).Activate
wb1.ActiveSheet.myrange.Select
Selection.Paste
Next i
End Sub
Community
  • 1
  • 1
diadarma
  • 13
  • 4

3 Answers3

1

The myrange variable is a range reference but you are using it like a string variable. You can actually do away with the Select method and use this:

Private Sub Insert(wb2 As Workbook, wb1 As Workbook)
    Dim myrange As String
    myrange = "B2:GT22"
    For i = 1 To 24
        wb2.Worksheets(i).Range(myrange).Copy 
        wb1.Worksheets(i + 1).Range(myrange).Paste
    Next i
End Sub
ChipsLetten
  • 2,923
  • 1
  • 11
  • 28
1

Another good reason why you should not use .Select

Is this what you are trying?

Private Sub Insert(wb2 As Workbook, wb1 As Workbook)
    Dim FromRng As Range, ToRng As Range
    Dim i As Long

    For i = 1 To 24
        Set FromRng = wb2.Worksheets(i).Range("B2:GT22")
        Set ToRng = wb1.Worksheets(i + 1).Range("B2:GT22")

        myrange.Copy ToRng
    Next i
End Sub
Community
  • 1
  • 1
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
0

take a look at place where you define MyRange before the error, first you define it then later on you activate another sheet and try to access MyRange while it is in previous sheet, that generates error, set MyRange after the :

 wb2.Worksheets(i).Activate

and it will work

KKowalczyk
  • 333
  • 2
  • 7