2013-06-26 248 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做类似的事情。