Прикрепил все CSV-файл, "Ожидаемая ошибка конца оператора" в моей строке Dir? - PullRequest
1 голос
/ 08 мая 2019

Я запускаю скрипт для автоматической отправки писем с вложениями. Все вложения будут иметь расширение .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.

Любая помощь будет оценена.

Ответы [ 2 ]

1 голос
/ 08 мая 2019

Вы можете легко достичь своего результата без использования старого 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

Надеюсь, это поможет.

0 голосов
/ 08 мая 2019

Должно быть

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...