对象“_Global”的VBA方法“联盟”失败

我正在尝试写一个循环遍历文件夹中的所有工作簿的macros,并为每个工作簿发送一个符合标准的行范围的电子邮件。 当我运行macros时,它为第一个文件执行此操作,但在第二个文件中停止,出现对象“_Global”failed“的错误”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 

任何帮助将不胜感激!

您正在尝试使用以前的工作簿创build的相同范围的Union 。 您需要清除您处理的每个文件的rng2:

 WorkBk.Close savechanges:=True Set rng2 = Nothing '<---You just closed the workbook this range was built with. File = Dir()