简体   繁体   中英

Excel VBA - Error in code to copy to specific sheet, dependent on range

JNevill very kindly cleaned up and improved the macro i had put together, unfortunately its coming back with errors and i havent been able to get a response to the original post. Hopefully someone can pick up where he left off.

the fault i'm getting is - object variable or with block variable not set that is against line lastCell = Range("A" & Rows.Count).End(xlUp).Offset(1)

Sub Macro1()
'Make a variable to store the cell found
Dim lastCell as Range

'find the last cell in Column A of the active sheet
lastCell = Range("A" & Rows.Count).End(xlUp).Offset(1)

'Paste in the I16 value
lastCell.value = RangE("I16").value

'Grab whatever is hanging out in Column B next to the last cell and stick it in J20
Range("J20").value = lastCell.Offset(0,1).value 

'Test to see if I16 has value "R"
If Range("I16").value = "R" Then

    'Find the last row in Sheet7, Column B and store it to the variable
    lastCell = Range("B" & Rows.Count).End(xlUp).Offset(1)

    'Copy J20 value to the lastCell in Sheet 7, Column B
    lastCell = Range("J20").value
End if


End Sub

original post is here ORIGINAL

You're just missing Set (since it's an object variable):

Set lastCell = Range("A" & Rows.Count).End(xlUp).Offset(1)

Based on comments below, I think this is the sort of thing you want:

Sub Macro1()
    Dim ws                    As Worksheet
    'Make a variable to store the cell found
    Dim lastCell              As Range

    'find the last cell in Column A of the active sheet
    Set lastCell = Range("A" & Rows.Count).End(xlUp).Offset(1)

    'Paste in the I16 value
    lastCell.Value = Range("I16").Value

    'Grab whatever is hanging out in Column B next to the last cell and stick it in J20
    Range("J20").Value = lastCell.Offset(0, 1).Value

    'Test to see if I16 has value "R"
    Select Case VBA.UCase$(Range("I16").Value2)
        Case "R"
            Set ws = sheet7
        Case "C"
            Set ws = sheet3
        Case "P"
            Set ws = Sheet1
        Case "S"
            Set ws = Sheet2
    End Select

    If Not ws Is Nothing Then
        'Find the last row in Sheet7, Column B and store it to the variable
        Set lastCell = ws.Range("B" & Rows.Count).End(xlUp).Offset(1)

        'Copy J20 value to the lastCell in Sheet 7, Column B
        lastCell = Range("J20").Value
        Application.Goto lastCell, True
    End If

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM