对象变量或块变量未设置91 VBA

时间:2016-10-19 14:58:59

标签: excel vba excel-vba macros

我正在处理一个宏,该宏应该将数据传输到另一个名为" pistoia"这是代码:

Sub SetCounter(ByVal counter As Double, ByVal product As String)
Dim ws As Worksheet
On Error Resume Next
Sheets("pistoia").Activate
Set ws = ActiveWorkbook.Sheets("pistoia")
On Error GoTo 0
    If ws Is Nothing Then
        MsgBox "pistoia sheet not found"
    Else
        If ws.Name = ActiveWorkbook.ActiveSheet.Name Then
            Dim index_destRow As Integer, index_destColumn As Integer, search_product As Range
            Rows(2).Find(What:="Nome commerciale", LookAt:=xlWhole, LookIn:=xlValues).Offset(2).Select
        Else
            MsgBox "pistoia sheet found but is inactive"
        End If
    End If
End Sub

错误在行上升:"行(2).Find(What:=" Nome commerciale",LookAt:= xlWhole,LookIn:= xlValues).Offset(2)。选择",我认为错误是由于新工作表的激活,因为在起始工作表中的前一个宏""我在导致错误的行中运行相同的操作。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

这告诉我,没有找到该值,因此它试图选择不存在的东西。例如。设置范围变量以检查找到的值。使用Find,如果它们不符合您的预期,也值得指定其他一些参数。

    Sub SetCounter(ByVal counter As Double, ByVal product As String)

    Dim ws As Worksheet, index_destRow As Integer, index_destColumn As Integer, search_product As Range
    Dim rFind As Range

    On Error Resume Next
    Sheets("pistoia").Activate
    Set ws = ActiveWorkbook.Sheets("pistoia")
    On Error GoTo 0

    If ws Is Nothing Then
        MsgBox "pistoia sheet not found"
    Else
        If ws.Name = ActiveWorkbook.ActiveSheet.Name Then
            Set rFind = ws.Rows(2).Find(What:="Nome commerciale", LookAt:=xlWhole, LookIn:=xlValues, MatchCase:=False, SearchFormat:=False)
            If Not rFind Is Nothing Then
                rFind.Offset(2).Select
            Else
                msgbox "Value not found"
            End If
        Else
            MsgBox "pistoia sheet found but is inactive"
        End If
    End If

    End Sub