Excel Vba Сохранить файл по заданному пути на основе статической переменной - PullRequest
1 голос
/ 09 июня 2019

Я пытаюсь изменить ниже, чтобы фактически вместо этого спрашивать путь, который он должен сохранить к заранее определенному пути на основе статической переменной + динамической переменной из ячейки.

Если папка не существует, ее следует создать.

Cansomeone поможет мне, как это изменить, поскольку я не гуру VBA, и я не могу найти правильного решения вообще.

Sub Pdf_To_EMail()
Dim xSht As Worksheet
Dim xFileDlg As FileDialog
Dim xFolder As String
Dim xYesorNo As Integer
Dim xOutlookObj As Object
Dim xEmailObj As Object
Dim xUsedRng As Range
Dim xStr As String
Dim xlSht As Excel.Worksheet

Set xSht = ActiveSheet
Set xFileDlg = Application.FileDialog(msoFileDialogSaveAs)

If xFileDlg.Show = True Then
xFolder = xFileDlg.SelectedItems(1)

Else

MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"

Exit Sub
End If

xStr = Format(Now(), "yyyy-mm-dd-hh-mm-ss")
xFolder = xFolder + "\" + xSht.Name + "-" + xStr + ".pdf"


If Len(Dir(xFolder)) > 0 Then

xYesorNo = MsgBox(xFolder & " already exists." & vbCrLf & vbCrLf & "Do you want to overwrite it?", _
vbYesNo + vbQuestion, "File Exists")
On Error Resume Next
If xYesorNo = vbYes Then

Kill xFolder
Else

MsgBox "if you don't overwrite the existing PDF, I can't continue." _
& vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Exiting Macro"

Exit Sub
End If
If Err.Number <> 0 Then
MsgBox "Unable to delete existing file. Please make sure the file is not open or write protected." _

& vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Unable to Delete File"

Exit Sub
End If
End If

Set xUsedRng = xSht.UsedRange
If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then

'Zapisz jako plik PDF

xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xFolder, Quality:=xlQualityStandard

Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)
With xEmailObj

.Display False
.To = "Email@Email.com"
.CC = ""
.Subject = "”
.Body = ":"
.Attachments.Add xFolder
If DisplayEmail = False Then
.Send
End If
End With
Else
MsgBox "The active worksheet cannot be blank"
Exit Sub
End If
End Sub
</code>

1 Ответ

0 голосов
/ 09 июня 2019

Это должно работать:

В настоящее время он будет проверять папку на вашем рабочем столе и Activesheet.Range("B2"), но вы можете изменить их оба в String Formation xFolder

Sub Pdf_To_EMail()
Dim xSht As Worksheet
Dim xFileDlg As FileDialog
Dim xFolder As String
Dim xYesorNo As Integer
Dim xOutlookObj As Object
Dim xEmailObj As Object
Dim xUsedRng As Range
Dim xStr As String
Dim xlSht As Excel.Worksheet


Set xSht = ActiveSheet

''''New Code to detect if folder Exists

Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

xFolder = Environ("USERPROFILE") & "\Desktop\" & xSht.Range("B2").Value '''' Change you path and cell Range

    If objFSO.FolderExists(xFolder) Then
        'do nothing
    Else
        objFSO.CreateFolder (xFolder)  '
    End If


xStr = Format(Now(), "yyyy-mm-dd-hh-mm-ss")
xFolder = xFolder + "\" + xSht.Name + "-" + xStr + ".pdf"


If Len(Dir(xFolder)) > 0 Then

xYesorNo = MsgBox(xFolder & " already exists." & vbCrLf & vbCrLf & "Do you want to overwrite it?", _
vbYesNo + vbQuestion, "File Exists")
On Error Resume Next
If xYesorNo = vbYes Then

Kill xFolder
Else

MsgBox "if you don't overwrite the existing PDF, I can't continue." _
& vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Exiting Macro"

Exit Sub
End If
If Err.Number <> 0 Then
MsgBox "Unable to delete existing file. Please make sure the file is not open or write protected." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Unable to Delete File"

Exit Sub
End If
End If

Set xUsedRng = xSht.UsedRange
If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then

'Zapisz jako plik PDF

xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xFolder, Quality:=xlQualityStandard

Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)

    With xEmailObj
        .Display False
        .To = "Email@Email.com"
        .CC = ""
        .Subject = "”"
        .Body = ":"
        .Attachments.Add xFolder
        If DisplayEmail = False Then
        .Send
        End If
    End With

Else
    MsgBox "The active worksheet cannot be blank"
    Exit Sub
End If

End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...