2014-04-02 53 views
1

我的代碼給了我一個必選對象424錯誤在這條線:VBA Excel的「必選對象」錯誤

lngRow = .Cells(.Rows.Count, 1).End(xlUp).Row 

我全碼:

Private Sub Worksheet_Change(ByVal Target As Range) 
' If Target.Count > 1 Then Exit Sub 
' If Target.Column > 2 Then Exit Sub 

    Application.EnableEvents = False 

    If Target.Column = 6 Then 
     If Target.Offset(0, 1).Value <> "" Then 
      MsgBox "You must only fill in one of the two columns" 
      Target.ClearContents 
      GoTo ExitSub 
     End If 
    End If 

    If Target.Column = 7 Then 
     If Target.Offset(0, -1).Value <> "" Then 
      MsgBox "You must only fill in one of the two columns" 
      Target.ClearContents 
      GoTo ExitSub 
     End If 
    End If 

    Dim arrData() As Variant 
    Dim i As Long 
    Dim lngRow As Long 
    Dim myNum As Variant 
    Dim ws As Worksheet 
    myNum = Target.Value 

    If Target.Column = 6 Then 
    With BogieInspectionPoints 'this is a sheet name 
     lngRow = .Cells(.Rows.Count, 1).End(xlUp).Row 
     arrData = .Range("a1:b" & lngRow) 
    End With 
    End If 

    If Target.Column = 7 Then 
    With WagonInspectionPoints 'this is a sheet name 
     lngRow = .Cells(.Rows.Count, 1).End(xlUp).Row 
     arrData = .Range("a1:b" & lngRow) 
    End With 
    End If 

    For i = 1 To lngRow 
     If myNum = arrData(i, 1) Then 
      Cells(Target.Row, 8).Value = arrData(i, 2) 
      Exit For 
     End If 
    Next 

    ExitSub: 
    Application.EnableEvents = True 

    End Sub 
+0

什麼是「BogieInspectionPoints」?它是表單名稱還是vba表單對象? –

+0

什麼是BogieInspectionPoints或WagonInspectionPoints? –

+0

這些確實是表名! – Jack

回答

0

它看起來像那些表變量不是組。

您需要在頂部添加此項。

Dim BogieInspectionPoints as Worksheet 
Dim WagonInspectionPoints as Worksheet 

Set BogieInspectionPoints = ActiveWorkbook.Sheets("BogieInspectionPoints") 
Set WagonInspectionPoints = ActiveWorkbook.Sheets("WagonInspectionPoints") 

我假設有其他代碼。當您添加此行時,所有With陳述應該使用您發佈的代碼正確處理。

你在做什麼With語句是短暫的對象。而不是寫

BogieInspectionPoints.Range("A1") 

「更多代碼

你可以寫

With BogieInspectionPoints 
.Range("A1") 
End With 

它使你不必編寫對象的全稱出來。

+0

我怎麼能當我刪除第6列或第7列中的數字時,讓Excel刪除第8列中的文本? – Jack