对象变量或带块变量不使用find函数在循环中设置

时间:2015-06-17 19:15:34

标签: vba excel-vba loops object find

Sub Main()
Dim FName As Variant, R As Long, DirLoc As String, i As Integer
R = 1
i = 1
DirLoc = ThisWorkbook.Path & "\" 'location of files
FName = Dir(DirLoc & "*.csv")
Do While FName <> ""
    ImportCsvFile DirLoc & FName, ActiveSheet.Cells(R, 1)
    R = ActiveSheet.UsedRange.Rows.Count + 1
    FName = Dir
    For i = 1 To 100
        Worksheets("RAW").Range("B1:B6").Copy
        Worksheets("filtered").Range("A" & Rows.Count).End(xlUp).Offset(1).PasteSpecial , Transpose:=True
        Cells.Find(What:="Run:", After:=Cells(1, 1), _
            LookIn:=xlValues, LookAt:=xlPart, _
            SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False).Select
        Worksheets("filtered").Cells(10, 10).Value = i
        If ActiveCell <> "Run:" & i Then
            Exit For
        End If
    Next i
    DeleteFiltered
Loop
End Sub

我遇到麻烦,因为我收到了错误:

           `Cells.Find(What:="Run:" & i, After:=Cells(1, 1), _
            LookIn:=xlValues, LookAt:=xlPart, _
            SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False).Select`

当我删除&#34;&amp ;;时,不会发生错误I&#34 ;.我用它来导入一个数据文件,然后找到一个特定的&#34;运行:1。&#34;然后它应该复制数据并找到下一个Run,然后是那个。这就是为什么我需要&amp;一世。我怎样才能做到这一点?

还有一些代码部分肯定没问题,所以我把它们排除了。

1 个答案:

答案 0 :(得分:2)

如果Cells.Find(What:="Run:" & i,...找不到匹配项,则语句的Select部分将导致错误。您应该始终将Find的结果存储在范围变量中,然后对Nothing进行测试。

将此声明添加到您的代码中:

Dim cellsFound As Range

并替换它:

    Cells.Find(What:="Run:", After:=Cells(1, 1), _
        LookIn:=xlValues, LookAt:=xlPart, _
        SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Select
    Worksheets("filtered").Cells(10, 10).Value = i
    If ActiveCell <> "Run:" & i Then
        Exit For
    End If

使用:

Set cellsFound = Worksheet("sheet_name").Cells.Find(What:="Run:" & i, After:=Worksheet("sheet_name").Cells(1, 1), _
        LookIn:=xlValues, LookAt:=xlPart, _
        SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)
If Not(cellsFound Is Nothing) Then
    Worksheets("filtered").Cells(10, 10).Value = i
Else
    ' not found
    Exit For
End If