我正在运行一个脚本,以自动发送带有附件的电子邮件。所有附件的扩展名均为.csv
。
我不知道文件的名称。我正在使用Dir语句,但遇到了一些问题。
我尝试将Dir语句分解为不同的字符串,但这也不起作用。
Dim cAttachment As String
Dim Folder As String
Dim fileCriteria As String
Folder = "C:\Users\____\Desktop\Test Folder"
fileCriteria = ".csv"
cAttachment = Dir(Folder & "\*" & fileCriteria)
我也尝试过:
Dim cAttachment As String
cAttachment = Dir("C:\Users\___\Desktop\Test Folder\*.csv")
在Dir语句的前括号中,我收到了预期的语句结尾错误。
任何帮助将不胜感激。
答案 0 :(得分:1)
您无需使用旧的Dir()
Function
就可以轻松实现结果。为此,您需要使用"Scripting.FileSystemObject"
。
这是用于在特定文件夹中发现扩展名为.csv
的所有文件的代码:
Dim oFile As Object
Dim oFSO As Object
Dim oFolder As Object
Dim oFiles As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("C:\my\Folder\") 'Set this accordingly
Set oFiles = oFolder.Files
'For all files in the folder
For Each oFile In oFiles
If (oFile Like "*.csv") Then
'Add this file to attachments
objMessage.AddAttachment oFile.Path
End If
Next
希望这会有所帮助。
答案 1 :(得分:0)
应该是
Folder = "C:\Users\____\Desktop\Test Folder\" cAttachment = Dir(Folder & "*.csv")` '// Loop to attch Do While Len(cAttachment ) > 0 .Attachments.Add Folder & cAttachment Atmt_File = Dir Loop
完整示例代码
Option Explicit
Private Sub Example()
Dim olMsg As Outlook.MailItem
Dim olRecip As Outlook.Recipient
Dim Atmt_Path As String
Dim olInsp As Outlook.Inspector
Dim wdDoc As Object
Dim rng As Object
Dim Atmt_File As String
'// Attachments Path.
Atmt_Path = "C:\Temp\"
'// Create the message.
Set olMsg = Application.CreateItem(olMailItem)
With olMsg
.Display '// This line must be retained
Atmt_File = Dir(Atmt_Path & "*.csv")
'// Loop to attch
Do While Len(Atmt_File) > 0
.Attachments.Add Atmt_Path & Atmt_File
Atmt_File = Dir
Loop
'// Cancell email if no files to send
If .Attachments.Count = 0 Then
'MsgBox "There are no reports to attach.", vbInformation
.Close 0
.Delete
Else
'// Add the To recipient(s)
Set olRecip = .Recipients.Add("0m3r@email.com")
Set olRecip = .Recipients.Add("0m3r@email.com")
olRecip.Type = olTo
'// Add the CC recipient(s)
Set olRecip = .Recipients.Add("0m3r@email.com")
olRecip.Type = olCC
'// Set the Subject, Body, and Importance of the message.
.Subject = "Reports - " & Format(Now, "Long Date")
.Importance = olImportanceHigh '// High importance
.BodyFormat = olFormatHTML
'// Edit the message body.
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
'// Set message body (to retain the signature)
Set rng = wdDoc.Range(0, 0)
'// add the text to message body
rng.Text = "Files are Attached, Thank you" & vbCrLf & vbCrLf
'// Resolve each Recipient's name.
For Each olRecip In .Recipients
olRecip.Resolve
If Not olRecip.Resolve Then
olMsg.Display
End If
Next
' .Send '//This line optional
End If
End With
End Sub