我正在尝试编写一个循环遍历文件夹中所有工作簿的宏,并且每个宏都会发送一封包含符合条件的行的电子邮件。当我运行宏时,它对第一个文件执行此操作,但在第二个文件处停止,给出对象'_Global'失败的错误“Method'Union',指向”Set rng2 = Union(rng2,row)“行。以下是相关代码:
Sub LoopThroughFiles()
Dim File As String
File = Dir("FilePath\")
While (File <> "")
Set WorkBk = Workbooks.Open("FilePath\" & File)
Dim rng As Range
Dim row As Range
Dim rng2 As Range
Dim strbody As String
Dim OutApp As Object
Dim OutMail As Object
Set rng = Range("B52:I200")
For Each row In rng.Rows
If row.Columns(7) >= Date Then
If Not rng2 Is Nothing Then
'Below is the line that gets the error
Set rng2 = Union(rng2, row)
Else
Set rng2 = row
End If
End If
Next
'Email code removed
WorkBk.Close savechanges:=True
File = Dir()
Wend
End Sub
非常感谢任何帮助!
答案 0 :(得分:3)
您尝试的Union
范围与使用之前的工作簿构建的范围相同。您需要为您处理的每个文件清除rng2:
WorkBk.Close savechanges:=True
Set rng2 = Nothing '<---You just closed the workbook this range was built with.
File = Dir()