2015-10-23 78 views
2

我在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的方式嗎?

+0

這可能是'.Find(...)'在前面的線方法沒有找到任何東西。在這種情況下,'nameRange'將被設置爲'Nothing'。你可以添加一些代碼來測試/處理它。 – xidgel

+0

不是,這很可能是因爲你的'.Find'方法沒有找到結果並返回'Nothing',所以你有錯誤!在你的'Set nameRange','MsgBox membership.Range(「A:A」)。Find(「user -name」)是Nothing'之前加上這行,如果它顯示'True',find方法找不到任何東西,如果它是'假'這個問題在別的地方! ;) – R3uK

回答

2

在代碼中有後續Find操作,該代碼僅指定查看整個單元格。此設置將持續存在,所以你可能只需要指定不看整個小區在第一Find電話:

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

第二次運行時,「user-name」是否存在?

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

檢查nameRange返回的引用,(我認爲),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返回一個引用到同一細胞中,從而可以直接拉回來的那個值?

相關問題