2016-10-03 77 views
0

我试图编写一个宏,它循环遍历文件夹中的所有工作簿,并为每个人发送符合条件的行范围的电子邮件。当我运行宏时,它为第一个文件执行此操作,但在第二个文件中停止,出现对象'_Global'failed'的方法'联合'错误,指向“Set rng2 = Union(rng2,row)”行。以下是相关的代码:对象'_Global'的VBA方法“联盟”失败

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 

任何帮助将不胜感激!

回答

3

您试图Union与您使用以前的工作簿构建的范围相同。您需要清除您处理的每个文件的rng2:

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