"对象未设置"错误

时间:2015-10-23 14:56:05

标签: excel vba excel-vba object

我在Excel VBA中有一个宏,它给了我一个错误。我在启动Excel后第一次运行它并且它运行得很好但是当我尝试在它之后的任何时候运行它它会在行nameRow = nameRange.Row上出错而给出错误Object not set并且我真的困惑为什么。

Sub AssignGroups()

    Dim membership As Worksheet
    Dim wb As Workbook
    Dim groups As Worksheet
    Dim nameRow As Long
    Dim fullNameString As String
    Dim nameRange As Range
    Dim groupRange As Range
    Dim nameRange2 As Range
    Dim nameIndex As Long
    Dim userNameString As String
    Dim barIndex As Long



    Set wb = ActiveWorkbook
    Set membership = Sheets("User Group Membership")
    Set groups = Sheets("User Assigned to Groups")

    membership.Activate
    Set nameRange = membership.Range("A:A").Find("user -name")
    nameRow = nameRange.Row
    fullNameString = membership.Cells(nameRow, "A").Value
    nameIndex = InStr(fullNameString, "user -name")
    barIndex = InStr(fullNameString, "|")
    userNameString = Mid(fullNameString, nameIndex + 12, ((barIndex - 4) - (nameIndex + 12)))

    groups.Activate
    Set nameRange2 = groups.Range("A:CH").Find(userNameString)
    nameColumn = nameRange2.Column



    membership.Activate
    membership.Cells(nameRow, "A").Activate

    Do
        ActiveCell.Offset(1).Activate

        If Not IsEmpty(ActiveCell.Value) Then

            cellValue = ActiveCell.Value
            groups.Activate
            Set groupRange = groups.Range("A:CH").Find(cellValue, , , lookat:=xlWhole)
            groupRow = groupRange.Row
            groups.Cells(groupRow, nameColumn).Activate
            ActiveCell.Value = "X"
            membership.Activate

         End If



        Loop Until IsEmpty(ActiveCell.Value)




End Sub

可能是因为我引用ActiveCell

的方式

2 个答案:

答案 0 :(得分:2)

您在代码中执行了后续Find操作,该操作仅指定查看整个单元格。此设置将保持不变,因此您可能只需指定不在第一个Find调用中查看整个单元格:

Set nameRange = membership.Range("A:A").Find(What:="user -name", Lookat:=xlpart)

答案 1 :(得分:0)

" user -name"第二次运行时存在吗?

 Set nameRange = membership.Range("A:A").Find("user -name")
    nameRow = nameRange.Row
    fullNameString = membership.Cells(nameRow, "A").Value

检查nameRange是否返回引用,并且(我认为),FIND会记住上次使用它的时间,因此可能会查看上一个FIND下面的单元格(请参阅下面的代码):

Dim nameRange As Range

Set nameRange = membership.Range("A:A").Find( _
    What:="user -name", _
    After:=membership.Range("A1"), _
    SearchDirection:=xlNext)

If Not nameRange Is Nothing Then
    'Do stuff if namerange found.
End If

这行不会返回与nameRange相同的值吗?

fullNameString = membership.Cells(nameRow, "A").Value

你告诉它在nameRow行返回A列中的值,而nameRange返回对同一个单元格的引用,那么只能拉回那个值吗?