2015-09-02 151 views
-1

我是新來的宏,並希望從工作表中的範圍中找到文本或文本的一部分,我研究並發現此代碼:VBA Excel宏運行時錯誤'1004'當試圖.Find()

Set aCell = .Columns(1).Find(What:="Custom ", LookIn:=xlValues, _ 
       LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
       MatchCase:=False, SearchFormat:=False) 

但是,當我運行,它給了我1004錯誤。所以這是我的全部子:

Sub kl() 
    Dim ws As Worksheet 
    Dim aCell As Range 

    Set ws = ThisWorkbook.Sheets("te-dhenat") 

    With ws 
     Set aCell = .Columns(1).Find(What:="Custom ", LookIn:=xlValues, _ 
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
        MatchCase:=False, SearchFormat:=False) 
     If Not aCell Is Nothing Then 
      aCell.Value = "Test" 
     Else 
      MsgBox "Not Found" 
     End If 
    End With 

End Sub 

我覺得代碼看起來很好,所以我不知道爲什麼Excel是顯示這個錯誤,請幫忙,謝謝你提前

+0

代碼看起來確定。它失敗的是什麼? – brettdj

+0

表單是否受到保護? – Rory

+0

@brettdj,它在set aCell上的失敗= .Columns(1).Find(..... –

回答

0

代碼

aCell.Value = "Test" 

將導致事件代碼再次執行!

請參閱this頁面,查找「防止事件循環」部分。

如果有其他信息值得一讀。

所以加入類似這樣的代碼:

Private Sub Worksheet_Change(ByVal Target As Range) 
    Application.EnableEvents = False 
    Target.Value = Target.Value + 1 
    Application.EnableEvents = True 
End Sub 
+0

我試過了,非常感謝 –