0

我收到一个运行时错误 91。我知道这通常是因为没有正确设置范围,但在这种情况下我只引用了一个工作表。为什么我会收到此错误?该代码应该创建一个新列并将其命名为“公司名称”。

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
4

2 回答 2

1

因为如果工作表名称不像“ Sheet ”,它仍然会使用第二个来查找 customer_name FIND,并且很可能不会找到它,并在尝试选择未找到的内容时给您一个错误。

你需要的是这样的:

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
于 2013-06-26T19:50:20.660 回答
0

Find方法返回 a 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

于 2013-06-26T19:47:43.293 回答