运行时错误' 91&#39 ;;对象变量或未设置块变量

时间:2015-06-01 21:59:19

标签: excel vba excel-vba

我收到以下错误:

  

"运行时错误' 91&#39 ;;对象变量或未设置块变量"

从方法" CreateArray()"中编写的特定代码,当它从NewEntry()方法中调用时:

    With NameStart
    n = Range(.Offset(1, 0), .End(xlDown)).Rows.Count
    End With 

原始代码:

Sub CreateArray()

With NameStart
    n = Range(.Offset(1, 0), .End(xlDown)).Rows.Count
End With

ReDim PhoneName(n)

For i = 1 To n
    PhoneName(i) = NameStart.Offset(i, 0)
    PhoneNumber(i) = NumStart.Offset(i, 0)
Next i
End Sub

下一个方法:

Sub NewEntry()
Application.ScreenUpdating = False
Worksheets("Phone Data").Activate

NewName = InputBox("Please enter the new entry name using the " _
& "following format: Last, First", "New Name", "Smith, John")
If NewName = "" Then
    MsgBox "Please enter a name."
    Exit Sub
End If

NewNumber = InputBox("Please enter the 10-digit phone number for " _
        & NewName & " usin the following format: 1234567890", _
        "New Number", 1234567890)
        If NewNumber / 10 ^ 10 < 0.1 Or NewNumber / 10 ^ 10 > 1 Then
            MsgBox "Please enter a 10-digit number."
            Exit Sub
        End If
        Call CreateArray
            For i = 1 To n
                If PhoneName(i) = NewName Then
                MsgBox "There is already an entry for this person in the " _
                & "phone book."
                Exit Sub
            End If
        Next i

    NameStart.Offset(n, 0).Value = NewName
    NumStart.Offset(n, 0).Value = NewNumber
    Range(NameStart, NumStart.Offset(n, 0)).Select
        Selection.Sort Key1:=NameStart, Order1:=xlAscending
    Worksheets("Phonebook Welcome").Activate
        Application.ScreenUpdating = True
        MsgBox NewName & " has been added to the phone book."
End Sub

变量声明:

Public i As Integer
Public n As Integer
Private PhoneName() As String
Private PhoneNumber() As Double
Public NewName As String
Public NewNumber As Double
Public NameStart As Range
Public NumStart As Range

1 个答案:

答案 0 :(得分:1)

声明NameStart实际上并未NameStart引用任何工作表上的任何实际范围。在Set NameStart = Worksheets("Sheet1").Range("A1:D10")上使用可以调用方法之前,您需要将其设置为引用实际范围,如下所示:

NameStart

如果您碰巧定义了一个名为&#34; NameStart&#34;那么你仍然需要将它链接到Set NameStart = Range("NameStart")变量:

NameStart

如果你不这样做,那么d <- c("80%", "12,500") as.numeric(gsub("\\D", "", d)) ## [1] 80 12500 没有链接到任何东西,并且试图在其上调用方法会产生运行时错误