簡體   English   中英

對於每個循環,Excel 2007 VBA運行時錯誤為“ 91”

[英]Excel 2007 VBA run-time error '91' with For Each loop

我收到運行時錯誤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

因為如果工作表名稱與“工作 ”不同,它仍將使用第二個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

Find方法返回Range ,但如果未找到Nothing則返回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做類似的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM