2013-06-26 246 views
0

我收到一個運行時錯誤91.我知道這通常是從沒有正確設置範圍,但我只在這種情況下引用工作表。爲什麼我得到這個錯誤?該代碼應該創建一個新列並將其命名爲「公司名稱」。Excel 2007 VBA運行時錯誤'91'與For Each循環

Dim ws As Worksheet 

For Each ws In Sheets 
    If ws.Name Like "*Sheet*" Then ws.Rows(1).Find("customer_name",LookAt:=xlPart).EntireColumn.Select 
     Application.CutCopyMode = False 
     Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove 

     ws.Rows(1).Find("customer_name", LookAt:=xlPart).Offset(0, -1).Select >----error here 
     ActiveCell.Value = "company name" 
Next 

回答

1

因爲如果工作表名稱是不喜歡「」它仍然會尋找使用第二FIND CUSTOMER_NAME,它很可能不會被發現,並給你一個錯誤嘗試選擇一些沒有找到時, 。

你需要的是這樣的:

Sub Sample() 
Dim ws As Worksheet 

For Each ws In Sheets 
    If ws.Name Like "*Sheet*" Then 

     ws.Rows(1).Find("customer_name", LookAt:=xlPart).EntireColumn.Select 

     Application.CutCopyMode = False 
     Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove 

     ws.Rows(1).Find("customer_name", LookAt:=xlPart).Select '>----error here 
     ActiveCell.Value = "company name" 

    End If 
Next 
End Sub 

或者另一種方式重新編寫的子是:

Sub Sample() 
Dim ws As Worksheet 

For Each ws In Sheets 

    If ws.Name Like "*Sheet*" Then 

     With ws.Rows(1).Find("customer_name", LookAt:=xlPart) 

     .EntireColumn.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove 
     .Value = "company name" 

     End With 

    End If 
Next 
End Sub 
0

Find方法返回一個Range,但如果沒有找到返回Nothing。您需要使用Is Nothing對此進行解釋。

Dim rngFind As Range 

    Set rngFind = ws.Rows(1).Find("customer_name", LookAt:=xlPart) 
    If Not rngFind Is Nothing Then 
     rngFind.Offset(0, -1).Select 
    End If 

您需要爲之前使用的Find做類似的事情。