VBA 400错误 - 无法调试搜索/复制功能

时间:2012-02-09 06:35:21

标签: excel excel-vba vba

我是新手/学习VBA。对于这个问题,我在运行代码时没有收到调试按钮,所以我无法找到错误。当我运行下面的宏时,错误只是说'400',之后没有调试选项。

    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

您可以非常感谢任何可以识别的指针或错误!

2 个答案:

答案 0 :(得分:3)

您是否尝试过添加:

On Error GoTo error_handler
第一行代码上的

和:

Exit Sub

error_handler:
  MsgBox Err.Description

在“End Sub”之前。

答案 1 :(得分:0)

您应该测试ActiveCell是否在第一列。 Excel引发错误,因为Offset(0, -1)将不存在。

以下是代码解决方案:

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