运行时错误91:无法通过第二行运行

时间:2017-01-18 11:25:38

标签: excel vba excel-vba

以下是我正在处理的代码的一部分,它是宏的一部分。

在另一个基本相同的文件上也是如此。

宏在另一个文件上工作,而在另一个文件上,它没有,并且附带运行时错误'91'。

附件是代码:

shtData.Activate
Dim r As Integer
Dim strassured As String

r = 1
While ActiveSheet.Cells(r, 1) <> ""
    ActiveSheet.Cells(r, 1).Select

    strassured = ActiveCell.Value
    If shtWorkSpace.Range("B3").Value = strassured Then
        If shtWorkSpace.Range("A60").Value = "Pending" Then
            DataHandling.OverwriteDataTab (strassured)
            Exit Sub
        Else
            MsgBox "This assured name is already in the database. Assured Names must be unique!", vbCritical
            shtWorkSpace.Activate
            ActiveSheet.Range("A1").Select
            Exit Sub
        End If
    Else
        r = r + 1
    End If
Wend

1 个答案:

答案 0 :(得分:0)

我添加了答案,而不是提供如何定义和Set两个工作表(shtDatashtWorkSpace)。

但是,为了提供更好的编码实践,不需要Activate工作表,或使用SelectActiveCell。而是使用完全限定的RangeWorksheets

<强>代码

Sub Test()

Dim shtData As Worksheet
Dim shtWorkSpace As Worksheet
Dim r As Integer
Dim strassured As String

Set shtData = Worksheets("Data") '<-- modify "Data" to your sheet name
Set shtWorkSpace = Worksheets("Workspace") '<-- modify "Workspace" to your sheet name

r = 1
While shtData.Cells(r, 1) <> ""
    strassured = shtData.Cells(r, 1).Value

    If shtWorkSpace.Range("B3").Value = strassured Then
        If shtWorkSpace.Range("A60").Value = "Pending" Then
            DataHandling.OverwriteDataTab (strassured)
            Exit Sub
        Else
            MsgBox "This assured name is already in the database. Assured Names must be unique!", vbCritical
            shtWorkSpace.Activate
            ActiveSheet.Range("A1").Select '<-- not sure why you need to select the sheet and Range("A1")
            Exit Sub
        End If
    Else
        r = r + 1
    End If
Wend

End Sub