I wrote below code, this code upload all document from share drive into excel based on their naming convention.
However it's applicable for Pdf file only. can you please help me that how can i upload other ext file as well like outlook/word/excel?
Dim folderPath As String, fileName As String
Dim destCell As Range
With Worksheets("ABC")
folderPath = .Range("F7").Value
Set destCell = .Range("G12")
End With
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
Application.ScreenUpdating = False
fileName = Dir(folderPath & "ABC*.pdf")
Do While fileName <> vbNullString
destCell.Worksheet.OLEObjects.Add _
fileName:=folderPath & fileName, _
Link:=False, _
DisplayAsIcon:=True, _
IconFilename:="C:\windows\Installer\{AC76BA86-1033-F400-7760-000000000005}\_PDFFile.ico", _
IconIndex:=0, _
IconLabel:=fileName, _
Left:=destCell.Left, _
Top:=destCell.Top, _
Width:=150, _
Height:=5
Set destCell = destCell.Offset(, 1)
fileName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Document Uploaded Successfully..!!"
Something Like This?
Dim folderPath As String, fileName As String
Dim destCell As Range
With Worksheets("ABC")
folderPath = .Range("F7").Value
Set destCell = .Range("G12")
End With
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
Application.ScreenUpdating = False
fileName = Dir(folderPath & "ABC*.*")
Do While fileName <> vbNullString
destCell.Worksheet.OLEObjects.Add _
fileName:=folderPath & fileName, _
Link:=False, _
DisplayAsIcon:=True, _
IconFilename:="C:\windows\Installer\{AC76BA86-1033-F400-7760-000000000005}\_PDFFile.ico", _
IconIndex:=0, _
IconLabel:=fileName, _
Left:=destCell.Left, _
Top:=destCell.Top, _
Width:=150, _
Height:=5
Set destCell = destCell.Offset(, 1)
fileName = Dir
Loop
Application.ScreenUpdating = True
MsgBox "Document Uploaded Successfully..!!"
Related
Could someone sell me why I am getting a runtime error here?? I have almost this identical code in another project that works, and I cant figure out the issue.
Sub Create_PDF()
' Create and save .pdf
Dim pdfName As String
Dim myrange As String
myrange = Cells(Rows.Count, 6).End(xlUp).Address
Dim AccountNumber As String
AccountNumber = Right(A1, 3)
FullName = "P:\Public\Generated Letters\LTXN Export Spreadsheets\" & "AccountEnding" & AccountNumber & ".pdf"
'Sets the name and location for the new file
myrange = Cells(Rows.Count, 6).End(xlUp).Address
'sets the string end for the print area
With ActiveSheet.PageSetup
.PrintArea = "A1:" & myrange
.Orientation = xlLandscape
.Zoom = False
.FitToPagesTall = False
.FitToPagesWide = 1
End With
'Setting the spreadsheet to print active content with columns fit to single page
If Dir(FullName) <> vbNullString Then
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="P:\Public\Generated_Letters\LTXN_Export_Spreadsheets\" & "AccountEnding" & AccountNumber & " - " & Format(Now, "mm.dd.yyyy hh mm") & ".pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Else
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="P:\Public\Generated_Letters\LTXN_Export_Spreadsheets\" & "AccountEnding" & AccountNumber & Format(Now, "mm.dd.yyyy hh mm") & ".pdf" _
, Quality:=xlQualityMedium, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
'###This is where I am getting the runtime error and the file is not saving###
End Sub
Sub openFolder()
'Open the folder that we save the PDF to
Call Shell("explorer.exe" & " " & "P:\Public\Generated Letters\LTXN Export Spreadsheets\", vbNormalFocus)
End Sub
The one difference from the other project is that AccountNumber is a number and not text, but I figured in defining it as a string it shouldnt matter???
Try this:
Option Explicit
'use Const for fixed values
Const EXPORTS As String = "P:\Public\Generated Letters\LTXN Export Spreadsheets\"
Sub Create_PDF()
Dim ws As Worksheet, myRange As Range
Dim AccountNumber As String, dt As String, FullName As String, fName As String, sep As String
Set ws = ActiveSheet
AccountNumber = Right(ws.Range("A1").Value, 3) 'not just `A1`
With ActiveSheet.PageSetup
.PrintArea = "A1:" & ws.Cells(Rows.Count, 6).End(xlUp).Address
.Orientation = xlLandscape
.Zoom = False
.FitToPagesTall = False
.FitToPagesWide = 1
End With
dt = Format(Now, "mm.dd.yyyy hh mm")
fName = EXPORTS & "AccountEnding" & AccountNumber
If Len(Dir(fName & ".pdf")) > 0 Then sep = " - "
fName = fName & sep & dt & ".pdf"
'note there's no `xlQualityMedium` enumeration for `Quality`
ws.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fName, _
Quality:=xlQualityStandard, IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub
Sub openFolder()
'Folder paths with spaces need to be quoted....
Call Shell("explorer.exe" & " """ & EXPORTS & """", vbNormalFocus)
End Sub
I use a macro for over 2 years with no problems. The macro is simple - copy a table from an Excel file and paste it into a Word document. For a few days, I am struggling with a problem - after starting the macro
error 4198 is occurring.
After clicking Debug VBA highlights such part of the code:
myDoc.Paragraphs(17).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
When I click Continue, the macro is going to the end with no additional problems until the next iteration.
Here is the entire macro:
Sub Agent_info()
Dim w As MailMerge
Dim a As Integer
Dim NumberOfFiles As Integer
Dim sFileName As String
Dim xlTable As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Dim komorka As String
Dim my_xl As Excel.Workbook
Dim xlApp As Excel.Application
'NumberOfFiles = 3
NumberOfFiles = InputBox("Ile pism przygotować?", "Pytanie")
On Error GoTo ERR_Handler
Application.ScreenUpdating = False
Application.Visible = True
Set w = ActiveDocument.MailMerge
w.DataSource.ActiveRecord = wdFirstDataSourceRecord
Set xlApp = CreateObject("Excel.Application")
Dim xlPath As String
xlPath = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\ZAŁĄCZNIKI.xlsx"
xlApp.Visible = True
Set my_xl = xlApp.Workbooks.Open(xlPath)
Worksheets("info").Activate
Range("A1").Select
If Len(Dir("C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania"
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO"
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma"
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe", vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe"
End If
For a = 1 To NumberOfFiles
On Error Resume Next
Set xlApp = GetObject("Excel.Application")
Err.Clear
If xlApp Is Nothing Then Set xlApp = CreateObject("Excel.Application")
If Err.Number = 429 Then
MsgBox "Microsoft Excel could not be found, aborting."
End If
On Error GoTo 0
komorka = ActiveCell.Address
Do While ActiveCell.Value <> "Suma"
ActiveCell.Offset(1, 0).Select
Loop
ActiveCell.Offset(0, 1).Select
Set xlTable = Excel.Range(komorka, ActiveCell)
xlTable.Copy
Do While ActiveCell.Value <> "Zaległość"
ActiveCell.Offset(-1, 0).Select
Loop
ActiveCell.Offset(0, 1).Select
With w
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = a
.LastRecord = a
End With
.Execute Pause:=False
End With
Dim katalog As String
Dim folder As String
Dim sciezka1 As String
Dim sciezka2 As String
Dim PDF As String
Dim PDF2 As String
Dim nazwaPisma As String
Dim nazwa1 As String
Dim nazwa2 As String
katalog = w.DataSource.DataFields("NAZWA_PLIKU").Value
folder = w.DataSource.DataFields("DATA_DO_PISMA_rrrrmmdd").Value
'folder = Format(Date, "yyyy-mm-dd")
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog, vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog
End If
If Len(Dir("C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder, vbDirectory)) = 0 Then
MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder
End If
'MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog
'MkDir "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder
nazwaPisma = " informacja o stanie zaległości z dnia "
sciezka1 = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Pliki tymczasowe\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".docx"
sciezka2 = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder & "\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".docx"
PDF = "C:\Users\jbalce\Desktop\Wezwania\Wezwania\Gotowe pisma\" & katalog & "\" & folder & "\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".pdf"
PDF2 = "C:\Users\jbalce\Desktop\Wysyłka maili\Załączniki do wysłania\INFO\" & w.DataSource.DataFields("AGENT").Value & nazwaPisma & w.DataSource.DataFields("DATA").Value & ".pdf"
ActiveDocument.Parent.ScreenUpdating = False
ActiveDocument.SaveAs _
FileName:=sciezka1, _
FileFormat:=wdFormatXMLDocument, _
LockComments:=False, _
Password:="", _
AddToRecentFiles:=True, _
WritePassword:="", _
ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, _
SaveFormsData:=False, _
SaveAsAOCELetter:=False
ActiveDocument.Close
On Error Resume Next
Set WordApp = GetObject(class:="Word.Application")
Err.Clear
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
End If
On Error GoTo 0
WordApp.Visible = True
WordApp.Activate
Set myDoc = WordApp.Documents.Open(sciezka1)
myDoc.Paragraphs(17).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
'If Err.Number = 4198 Then
'MsgBox "Microsoft Word could not be found, aborting."
'End If
Set WordTable = myDoc.Tables(1)
WordTable.AutoFitBehavior (wdAutoFitWindow)
WordTable.Range.ParagraphFormat.SpaceAfter = 0
Set PasteSheet = Nothing
Documents(myDoc).SaveAs _
FileName:=sciezka2, _
FileFormat:=wdFormatXMLDocument, _
LockComments:=False, _
Password:="", _
AddToRecentFiles:=True, _
WritePassword:="", _
ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, _
SaveFormsData:=False, _
SaveAsAOCELetter:=False
ActiveDocument.ExportAsFixedFormat _
OutputFileName:=PDF2, _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, _
From:=1, To:=1, _
Item:=wdExportDocumentContent, _
IncludeDocProps:=True, _
KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, _
DocStructureTags:=True, _
BitmapMissingFonts:=True, _
UseISO19005_1:=False
ActiveDocument.ExportAsFixedFormat _
OutputFileName:=PDF, _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, _
From:=1, To:=1, _
Item:=wdExportDocumentContent, _
IncludeDocProps:=True, _
KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, _
DocStructureTags:=True, _
BitmapMissingFonts:=True, _
UseISO19005_1:=False
Documents(myDoc).Close
w.DataSource.ActiveRecord = wdNextRecord
Next
END_Handler:
Application.Visible = True
Application.ScreenUpdating = True
Exit Sub
ERR_Handler:
MsgBox Err.Description
Resume END_Handler:
End Sub
I already have a code that do the exporting to PDF, it exports the selected sheets but I want to make the exported selection in the sheets bigger in the PDF file, to help the printing phase later.
Here's the code that do the exporting:
Sub PDFActiveSheet()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strTime = Format(Now(), "yyyymmdd\_hhmm")
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
strFile = strName & "_" & strTime & ".pdf"
strPathFile = strPath & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "Les QrCodes ont été exporter dans le fichier PDF" _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Erreur lors de l'exportation"
Resume exitHandler
End Sub
If you simply want to zoom in by a fix %, use the following command before the export line
wsA.PageSetup.Zoom = 150
I have cobbled together a VBA script that loops through a list of data, changing the value of a single cell on a summary page. That cell drives a number of formulas. After each iteration, the cell range of interest is saved off as a PDF.
I am looking to avoid having to manually hit enter every time the 'save as' dialog box is generated on each loop. Once I deploy this script, I could be looking at 1k+ iterations.
Sub AlterID()
Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
Set ws = Worksheets("Summary Data")
For Each c In Worksheets("Data").Range("A2:A11").Cells
Worksheets("Summary Data").Range("B1").Value = c.Value
strFile = ws.Range("D3").Value
strFile = ThisWorkbook.Path & "\" & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
ws.Range("D3:H9").Select
Selection.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End If
Next
End Sub
Sub AlterID()
Dim ws As Worksheet, c As Range
Dim strFile As String
Set ws = Worksheets("Summary Data")
For Each c In Worksheets("Data").Range("A2:A11").Cells
ws.Range("B1").Value = c.Value
strFile = ThisWorkbook.Path & "\" & ws.Range("D3").Value
ws.Range("D3:H9").ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
End Sub
Have you tried turning off application alerts?
Application.DisplayAlerts = False 'before your code
Application.DisplayAlerts = True 'after your code
Edit 1
Here is a sub I use to save a file to a PDF
Sub SaveAsPDF()
Dim myValue As Variant
Dim mySheets As Variant
mySheets = Array("Report")
For Each sh In mySheets
Sheets(sh).PageSetup.Orientation = xlLandscape
Next
uid = InputBox("Enter your UID")
uid = StrConv(uid, vbProperCase)
Application.PrintCommunication = False
With Sheets("Report").PageSetup
.FitToPagesWide = 1
.FitToPagesTall = False
End With
Application.PrintCommunication = True
Dim fName As String
fName = "HMB SOX report for week ending " & ActiveSheet.Range("H4").Text
Call selectPage("Report")
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, fileName:= _
"C:\Users\" & uid & "\Desktop\" & fName, :=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, Publish:=False
End With
End Sub
I'm working vba macro which works perfectly but I need save the documents as .pdf.
I´m searching for tips, but I don´t know how to find them. Last time I found this solution : vba mail merge save as pdf
but I don´t know apply it to my macro.
Here is my code:
Sub RunMerge()
Dim wd As Object
Dim wdocSource As Object
Dim strWorkbookName As String
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wdocSource = wd.Documents.Open(ThisWorkbook.Path & "\" & "ArtSpecDatabase.docx")
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
wdocSource.MailMerge.MainDocumentType = wdFormLetters
wdocSource.MailMerge.OpenDataSource _
Name:=strWorkbookName, _
AddToRecentFiles:=False, _
Revert:=False, _
Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
SQLStatement:="SELECT * FROM `Sheet2$`"
With wdocSource.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = 1
.LastRecord = 1
End With
.Execute Pause:=False
End With
Dim PathToSave As String
PathToSave = ThisWorkbook.Path & "\" & "pdf" & "\" & Sheets("Sheet2").Range("B2").Value2 & ".docx"
If Dir(PathToSave, 0) <> vbNullString Then
wd.FileDialog(FileDialogType:=msoFileDialogSaveAs).Show
Else
wd.activedocument.SaveAs2 PathToSave, wdFormatDocumentDefault
End If
wd.Visible = True
wdocSource.Close savechanges:=False
wd.activedocument.Close savechanges:=False
Set wdocSource = Nothing
Set wd = Nothing
End Sub
To export a Word document as PDF, you need to use the ExportAsFixedFormat method. For example, you can replace your SaveAs2 call with this:
wd.ActiveDocument.ExportAsFixedFormat PathToSave, 17 'The constant for wdExportFormatPDF
Now, your call to FileDialog makes no sense, so I propose changing the entire Dir(...) If-sentence to this:
Dim PathToSave As String
PathToSave = ThisWorkbook.Path & "\" & "pdf" & "\" & Sheets("Sheet2").Range("B2").Value2 & ".pdf"
If Dir(PathToSave, 0) <> vbNullString Then
With wd.FileDialog(FileDialogType:=msoFileDialogSaveAs)
If .Show = True Then
PathToSave = .SelectedItems(1)
End If
End With
End If
wd.ActiveDocument.ExportAsFixedFormat PathToSave, 17 'The constant for wdExportFormatPDF
EDIT: Forgot to include ".pdf" extension.
Use the below code to export excel to pdf
Sub tst1()
Dim fFilename As String
fFilename = "C:\Documents and Settings\test.xlsx"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
fFilename & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
End Sub