Home » excel » excel – VBA 400 Error – can't debug search/copy function

excel – VBA 400 Error – can't debug search/copy function

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m new/learning VBA. For this issue, I’m not getting a debug button when running my code, so I’m not able to find the error. The error just says ‘400’ when I run the macro below, with no debug option after.

    Sub Search_and_Copy_Discount_and_Shopper()
    Dim strStartingCell As String
    Dim strCustomer As String
    Dim strDiscount As String
    Dim strShopper As String

    'store starting place
    'look at column A, store value
    strStartingCell = ActiveCell.Address
    strCustomer = ActiveCell.Offset(0, -1).Value

    'go to customer sheet
    Sheets("Customer").Select
    Range("A2").Select

    'compare values in A to strCustomer
    'if it matches, copy cells 1 and 2 to the right in values
    'if no match, go down one cell and check again
    Do While IsEmpty(ActiveCell.Value) = False
        If ActiveCell.Value = strCustomer Then
            strDiscount = ActiveCell.Offset(0, 1).Value
            strShopper = ActiveCell.Offset(0, 2).Value
            Exit Sub
        Else
            ActiveCell.Offset(1, 0).Select
        End If
    Loop

    'go back to purchases sheet
    Sheets("Purchases").Select

    'copy in current cell and cell 1 to the right
    Range(strStartingCell).Select

    'paste strDiscount in current cell
    'paste strShopper in cell 1 to the right
    ActiveCell.Value = strDiscount
    ActiveCell.Offset(0, 1).Value = strShopper

End Sub

Any pointers or mistakes you can identify would be greatly appreciated!

How to&Answers:

Have you tried adding:

On Error GoTo error_handler

on the first line of code and:

Exit Sub

error_handler:
  MsgBox Err.Description

right before the “End Sub”.

Answer:

You should test if your ActiveCell is on the first column. Excel raises an error because the Offset(0, -1) won’t exist.

Here is a code solution:

Sub Search_and_Copy_Discount_and_Shopper()
Dim strStartingCell As String
Dim strCustomer As String
Dim strDiscount As String
Dim strShopper As String

'store starting place
'look at column A, store value
If Acticell.Column = 1 Then
    MsgBox ("You cannot pick a cell on column A")
    Exit Sub
End If
strStartingCell = ActiveCell.Address
strCustomer = ActiveCell.Offset(0, -1).Value

'end of your code