vba - 对象变量或带 block 变量未使用查找功能在循环中设置

标签 vba excel 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`

当我删除“& i”时,不会出现错误。我用它来导入数据文件,然后找到特定的“Run:1”。然后它应该复制数据并找到下一个运行以及之后的运行。这就是为什么我需要 & i。我怎样才能做到这一点?

还有一些代码部分绝对没问题,所以我将它们省略了。

最佳答案

如果 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

关于vba - 对象变量或带 block 变量未使用查找功能在循环中设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30900430/

相关文章:

vba - 使用 Excel VBA 获取发件人的 SMTP 电子邮件地址

vba - 简报 VBA : How to get last used column in a row from an Excel sheet

vba - 查找名称为 "x"的列并计算该列中出现的单词

python - While 循环仅正确迭代一次

vba - 如何在 PowerPoint VBA 中模拟 ThisPresentation

mysql - VBA脚本从MySql数据库读取时出现问题

c# - 从 c# Winform 运行 20 分钟的 Excel 宏

excel - 如何在 VBA 中将时间作为变量?

python - 使用python循环遍历字典中的值以根据键更改值

php - 如何使用 PHP 循环遍历按十年分组的记录的 MySQL 结果集?