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/