vba - 如果在外部文件中找不到,则查找中断

时间:2017-08-16 14:53:23

标签: vba excel-vba excel

有点简化,但基本上我想要的是在外部文件中找到多个字段(不打开它),如果找不到则有默认值。

我首先必须搜索字符串前缀,这有效,但我必须采用现有或不存在的结尾

这样的事情:

Set src = Workbooks.Open(CStr(FilePath & Filename), True, True)
Set wb = Application.ThisWorkbook.ActiveSheet
For Each Roww In Range("A3:A14").Rows
        With src.Worksheets(srcSheet)
            cellSearch = "*" & wb.Range("A" & Roww.Row) & "*)"
            cellSearch = Replace(cellSearch , " -C-", "")

            'this works
            cellVal = .Range("A:A").Find(What:=cellSearch , After:=.Range("A1"))

            'this breaks if not found
            findPlaceHolder = .Range("A:A").Find(What:=cellVal & ", UK", After:=.Range("A1"))

            If findPlaceHolder = "" Then
                wb.Range("E" & rowHelp) = 0
            Else
                wb.Range("E" & rowHelp) = findPlaceHolder
            End If

当然,很可能就是这样,第一个找到的只是因为它总是成功并找到所有字段。

1 个答案:

答案 0 :(得分:1)

你应该真正查找Find因为有大量文档可用。您还应养成声明变量并使用Option Explicit的习惯。您需要先检查是否找到了任何内容

Sub x()

Dim cellVal As Range, findPlaceHolder As Range

Set src = Workbooks.Open(CStr(FilePath & Filename), True, True)
Set wb = Application.ThisWorkbook.ActiveSheet
For Each roww In Range("A3:A14").Rows
        With src.Worksheets(srcSheet)
            cellSearch = "*" & wb.Range("A" & roww.Row) & "*)"
            cellSearch = Replace(cellSearch, " -C-", "")

            Set cellVal = .Range("A:A").Find(What:=cellSearch, After:=.Range("A1"))
            If Not cellVal Is Nothing Then
                Set findPlaceHolder = .Range("A:A").Find(What:=cellVal & ", UK", After:=.Range("A1"))
                If findPlaceHolder Is Nothing Then
                    wb.Range("E" & rowHelp) = 0
                Else
                    wb.Range("E" & rowHelp) = findPlaceHolder
                End If
            End If
        End With
Next roww

End Sub