【发布时间】:2017-12-23 06:00:35
【问题描述】:
我正在开展一个项目,以自动化带有 .msg 附件的 Outlook 邮件。发送这些邮件将通过 Excel 进行。我正在使用 VBA Excel 来做到这一点。
在 Excel 中,我有一列包含所需的电子邮件(T 列),另一列(R 列)包含 .msg 文件的一部分名称。文件名的一部分可以包含在一个或多个文件中。如果找到更多文件,则将它们全部邮寄到 T 列中确定的相应邮件。
我对 Excel VBA 有点陌生,但我有一个工作代码可以找到这些文件并将其放在 U 列中的路径中(如果发现两个文件,它们稍后会在代码中分隔在 U 列和V) 使用代码末尾的Outlook邮件发送路径。
我唯一的问题是这些文件分布在子文件夹中,我的代码只有在所有文件都在一个文件夹中时才有效。我使用 (DIR$) 来定位这些带有通配符的文件。如何优化代码以将文件定位在所有子文件夹而不是一个文件夹中?
Sub Send_Files()
Dim OApp As Object
Dim OMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
Dim irow As Integer
Dim i As Integer
Dim dpath As String
Dim pfile As String
Dim FileNames As String
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim Mail_Object, OutApp As Variant
Dim OutMail As Variant
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
On Error Resume Next
irow = 1
dpath = "H:\My Documents\test\"
Do While Cells(irow, 18) <> Empty
pfile = Dir$(dpath & "\*" & Cells(irow, 18) & "*")
FileNames = ""
'MsgBox pfile
Do Until LenB(pfile) = 0
If FileNames <> "" Then
FileNames = FileNames & ";" & dpath & pfile
Else
FileNames = dpath & pfile
End If
pfile = Dir$
For Each cell In Cells(irow, 18)
Cells(irow, 21) = FileNames
Next cell
Loop
irow = irow + 1
Loop
'Debug.Print FileNames
Application.DisplayAlerts = False
Columns("V:AU").Select
Selection.ClearContents
Columns("U:U").Select
Selection.TextToColumns Destination:=Range("U1"), DataType:=xlDelimited, _
TextQualifier:=xlNone, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=True, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Set sh = ActiveSheet
Set OApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("T").Cells.SpecialCells(xlCellTypeConstants)
Set rng = sh.Cells(cell.Row, 1).Range("U1:V1")
If cell.Value Like "?*@testmail.nl" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OMail = OApp.CreateItem(0)
With OMail
.To = cell.Value
.Body = "Hoi " & cell.Offset(0, -1).Value
.Subject = cell.Offset(0, -2).Value
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
'.Subject = FileCell.Value
End If
End If
Next FileCell
.Display
' Application.Wait (Now + TimeValue("0:00:01"))
' Application.SendKeys "%z"
End With
Set OMail = Nothing
End If
Next cell
Set OApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
【问题讨论】: