Quantcast
Channel: Excel Help Forum - Excel Programming / VBA / Macros
Viewing all articles
Browse latest Browse all 50057

Code fails with runtime error 91 in some case.

$
0
0
Hello.

I have pusseld together a code that matches data between ranges on different workbooks and copy pastes information belonging to sertain ranges from wb2 to wb1.

The code works just fine on sheet "Car" and "Bike" in MainWorkbook. but when run on a more complex sheet "Plane" i get runtime error 91 "objecvariable or with block variable has not been defined". still when i press debug and stop the code it highlights the copy functions for range nr 3. and when i stop code after error and close it, the macro has still done its job as intended.

Code i use is

Code:

Option Explicit

Sub Import()
Dim fname As String

Dim Crng As Range, Frng As Range, Irng As Range

Set Crng = ActiveSheet.Range("C7")
Set Crng = Range(Crng, Crng.End(xlDown))

Set Frng = ActiveSheet.Range("F7")
Set Frng = Range(Frng, Frng.End(xlDown))

Set Irng = ActiveSheet.Range("I7")
Set Irng = Range(Irng, Irng.End(xlDown))

fname = ActiveSheet.Name

Workbooks.Open FileName:=Range("M2")
Sheets(fname).Select

Dim Erng As Range, aCell As Range, bCell As Range

Set Erng = ActiveSheet.Range("E5")
Set Erng = Range(Erng, Erng.End(xlDown))

For Each aCell In Crng
    Set bCell = Erng.Find(What:=aCell, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    If Not aCell Is Nothing Then
        aCell.Offset(, -1) = bCell.Offset(, -1)
        aCell.Offset(, 1) = bCell.Offset(, -2)
    End If
    Next

For Each aCell In Frng
    Set bCell = Erng.Find(What:=aCell, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    If Not aCell Is Nothing Then
        aCell.Offset(, -1) = bCell.Offset(, -1)
        aCell.Offset(, 1) = bCell.Offset(, -2)
    End If
    Next

For Each aCell In Irng
    Set bCell = Erng.Find(What:=aCell, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    If Not aCell Is Nothing Then
        aCell.Offset(, -1) = bCell.Offset(, -1)
        aCell.Offset(, 1) = bCell.Offset(, -2)
    End If
    Next
   
ActiveWindow.Close

End Sub

Could anyone please help me find whats wrong and need be fixing?
All the help i can get is appriciated!

Cross Posts at http://www.ozgrid.com/forum/showthread.php?t=181410
& http://www.mrexcel.com/forum/excel-q...some-case.html

Cheers
Attached Files

Viewing all articles
Browse latest Browse all 50057

Trending Articles