2013-04-03 34 views
0

我在Excel中做了一個VB makro來執行一些東西,如果單元格在給定的範圍內,但是當我執行它時,它會給我一個錯誤,我不明白爲什麼。VB如果單元格在範圍內Excel

Private Sub Worksheet_Change(ByVal Target As Range) 
Dim isect As Boolean 
isect = Application.Intersect(Selection, Range("D11:D35")) 
If isect Then 
    If ActiveCell.Offset(-1, 0) - ActiveCell.Offset(-1, 1) > 2.5 Then 
     Range("A1:A1").Value = "ok" 
    End If 
End If 
End Sub 

的錯誤是:

Object variable or With block variable not set. 
+1

'如果不是沒有那麼'你也應該說明'Target'不總是一個單元:它可以是一個多單元的範圍...... – 2013-04-03 21:36:12

+0

你正在得到這個問題,因爲你的代碼試圖進入一個循環,因爲'Range(「A1:A1」)。Value =「ok」'。我會建議看到這個http://stackoverflow.com/questions/13860894/ms-excel-crashes-when-vba-code-runs/13861640#13861640也改變選擇'目標'編輯:此外蒂姆有一個有效點'目標不總是一個單元格所以你將不得不考慮這一點以及.. – 2013-04-03 21:41:14

+0

@TimWilliams感謝隊友'如果不是isect是沒有那麼'它的作品像一個魅力我怎麼能接受你的答案? – pocpoc47 2013-04-03 21:45:31

回答

0

更改前3行到:

Dim isect As Range 
Set isect = Application.Intersect(Selection, Range("D11:D35")) 
If Not isect Is Nothing Then 

但@Siddharth有關循環,這是非常重要的在這裏檢查還發表評論。

+0

該死的你是對的我還可以使用什麼比WorkSheet_Change? – pocpoc47 2013-04-03 21:55:38

+0

只是指[思想](http://stackoverflow.com/a/13861640/2143262)通過@Siddharth – 2013-04-03 21:58:34

+0

謝謝偉大的工作:) – pocpoc47 2013-04-03 22:11:17

0

的另一種方法,而無需使用Boolean Variable/Selection(也包含蒂姆的建議爲好)......

Private Sub Worksheet_Change(ByVal Target As Range) 
    On Error GoTo Whoa 

    Application.EnableEvents = False 

    If Target.Cells.CountLarge > 1 Then 
     MsgBox "More than 1 cell ws changed" 
    Else 
     If Not Intersect(Target, Range("D11:D35")) Is Nothing Then 
      If Target.Offset(-1, 0).Value - Target.Offset(-1, 1).Value > 2.5 Then 
       Range("A1").Value = "ok" 
      End If 
     End If 
    End If 

Letscontinue: 
    Application.EnableEvents = True 
    Exit Sub 
Whoa: 
    MsgBox Err.Description 
    Resume Letscontinue 
End Sub 

注:爲什麼.CountLarge?請參閱this

+0

謝謝你完美 – pocpoc47 2013-04-04 08:01:49

相關問題