Qualified Reference to Word Enumerations - vba

I built a macro in Outlook that refers to the Word object library.
The macro is very large and consists of several subs and functions. The end goal of this macro is to convert the selected Outlook mailitem into a PDF via (via Word) and combine it with all PDF attachments.
I keep getting a runtime error 462 "the remote server machine does not exist or is unavailable."
I have narrowed down the line where this error is occurring. Code as follows:
wdApp.Selection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(1.5), _
Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
As you can see, I am creating a qualified reference to the Word Application ("wdApp.Selection..."), but I suspect that somehow, I need to qualify the enumerators as well. How would I do this? Or if I am mistaken and the issue is with another part of the code, please let me know.
Here is the rest of my code (it is very lengthy).
Option Explicit
Sub wordToPDF()
' ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
' ANOTHER NOTE: you MUST disable sandbox protections in Adobe Acrobat or this
' macro will not work. You must uncheck "Enable Protected Mode at startup"
' within the "Sandbox Protections" section in the Adobe enhanced secutiy pref-
' erences.
' https://www.adobe.com/devnet-docs/acrobatetk/tools/AppSec/sandboxprotections.html#:~:text=Go%20to%20Edit%20%3E%20Preferences%20%3E%20Security,the%20feature%20controls%20as%20needed.
' ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
' Site below explains how to run Outlook VBA from Excel (applies here)
' https://hackernoon.com/how-to-create-word-documents-within-excel-vba-d13333jl
' Site below explains how to control multiple Office apps from one macro
' https://learn.microsoft.com/en-us/office/vba/excel/concepts/working-with- _
other -applications / controlling - one - microsoft - office - Application - From - another
On Error GoTo errHandler1
' Set "True" if you want to run macro in debug mode
Dim boolDebug As Boolean: boolDebug = False
If boolDebug Then
Debug.Print "#######################################################" & _
vbCrLf & "BEGINNING MACRO" & _
"#######################################################"
End If
'================================================================================
' Initialize variables
'================================================================================
' Declare OUTLOOK objects
Dim olSel As Outlook.Selection, olMI As Outlook.MailItem, _
olAtt As Outlook.Attachment, olAtts As Outlook.Attachments
' Declare WORD objects
Dim wdApp As Word.Application
Dim wdDocs As Word.Documents
Dim wdAllDocs As Word.Documents
Dim wdDoc As Word.Document
Dim wdItDoc As Word.Document
Dim rgSel As Variant
' Declare other objects/variabels
Dim myDate As String, olTempFolder As String, myPrinter As String, sUser As String, _
sFrom As String, sTo As String, sCC As String, sBCC As String, _
sSubj As String, dirExists As String, dirAttr As String, tempPath As String, _
myDialogueTitle As String, sFileNamePDF As String, attFullPath As String, _
sSenderEmail As String, arrHeader(1, 6) As String, sDay As String, sMonth As String, _
sFinalPDF As String, sPdfRoot As String
Dim dtSent As Date
Dim Shex As Object
Dim i As Integer
Dim vItem As Variant
' Set Outlook objects
Set olMI = GetCurrentItem ' Custom function
' Make day variable 2 characters in length
If Len(Day(Now)) < 2 Then
sDay = "0" & Day(Now)
Else
sDay = Day(Now)
End If
' Make month variable 2 characters in length
If Len(Month(Now)) < 2 Then
sMonth = "0" & Month(Now)
Else
sMonth = Month(Now)
End If
' Initialize date variable
myDate = Year(Now) & sMonth & sDay & Hour(Now) & Minute(Now) & _
Second(Now)
' Assign PDF printer to variable
myPrinter = "Adobe PDF"
' Assign the window title of the save as pdf dialogue
myDialogueTitle = "Save PDF File As"
'================================================================================
' Create email download path
'================================================================================
' Get the local temp folder path
tempPath = ""
tempPath = VBA.Environ("temp")
' Add Outlook Attachments subfolder to temp path
olTempFolder = tempPath & "\Outlook Attachments"
Debug.Print olTempFolder ' Print the folder path to immediate window
' If the path exists, check to make sure path is a directory, else create
dirExists = Dir(olTempFolder, vbDirectory)
If dirExists <> "" Then
dirAttr = GetAttr(olTempFolder)
' Check if path is directory (attribute "16")
If dirAttr <> 16 Then
MsgBox "There is an error with the specified path. Check code " & _
"try again."
Exit Sub
End If
Else
' If folder does not exist, create
MkDir (olTempFolder)
End If
'================================================================================
' Delete items older than 14 days
'================================================================================
Dim dNow, dLimit, dCreated As Date
Dim fso, fsoF, oSubFolder, oFile As Object
Dim sDebugFPath As String
' Assign current time and two weeks ago time
dNow = Now()
dLimit = DateAdd("d", -7, dNow)
' Get the outlook folder where items are being saved
Set fso = CreateObject("Scripting.FileSystemObject")
Set fsoF = fso.GetFolder(olTempFolder)
' Check each subfolder in temp outlook folder and delete if too old
For Each oSubFolder In fsoF.SubFolders
' Get date created of iteration subfolder
dCreated = oSubFolder.DateCreated
' If subfolder exceeds the file age limit, delete
If dCreated < dLimit Then
sDebugFPath = oSubFolder
Debug.Print oSubFolder
oSubFolder.Delete (True)
Debug.Print "Deleted the following folder: " & sDebugFPath
End If
Next
' Delete any non-folder files in the temporary outlook folder
For Each oFile In fsoF.Files
fso.deletefile oFile
Next
Set fso = Nothing
Set fsoF = Nothing
'================================================================================
' Create unique folder for this run
'================================================================================
olTempFolder = olTempFolder & "\emailToPDF-" & myDate
MkDir (olTempFolder)
'Set filename.pdf
sFileNamePDF = olTempFolder & "\!EmailMessage.pdf" '<-"!" for sorting
'================================================================================
' Save attachments from selected email
'================================================================================
For Each olAtt In olMI.Attachments
If Not isEmbedded(olAtt) Then
attFullPath = olTempFolder & "\" & olAtt.DisplayName
olAtt.SaveAsFile (attFullPath)
End If
Next
'================================================================================
' Initialize header variables
'================================================================================
' Get active user
Dim myNamespace As Outlook.NameSpace
Set myNamespace = Application.GetNamespace("MAPI")
sUser = myNamespace.CurrentUser
' Get sender email
sSenderEmail = getEmail(olMI)
' Assign header variables to array
arrHeader(0, 0) = "From:"
arrHeader(1, 0) = olMI.SenderName & " <" & sSenderEmail & ">" ' From
arrHeader(0, 1) = "Sent:"
arrHeader(1, 1) = olMI.ReceivedTime ' Rec'd Date/Time
arrHeader(0, 2) = "To:"
arrHeader(1, 2) = olMI.To ' To
arrHeader(0, 3) = "Cc:"
arrHeader(1, 3) = olMI.CC ' CC
arrHeader(0, 4) = "Bcc:"
arrHeader(1, 4) = olMI.BCC ' BCC
arrHeader(0, 5) = "Subject:"
arrHeader(1, 5) = olMI.Subject ' Subject
arrHeader(0, 6) = "Attachments:"
i = 0
For Each olAtt In olMI.Attachments ' Create string list of attachments
' If attachment is not embedded, add it to attachment string variable
If Not isEmbedded(olAtt) Then
' Add semicolon before any non-embedded attachments after the first
If i > 0 Then
arrHeader(1, 6) = arrHeader(1, 6) & "; "
End If
' Build attachment string within the header variable array
arrHeader(1, 6) = arrHeader(1, 6) & olAtt
i = i + 1
End If
Next
i = 0
If boolDebug Then
For Each vItem In arrHeader
Debug.Print vItem
Next
End If
'================================================================================
' Create word object and insert header
'================================================================================
' Set Word objects
'Set wdApp = GetObject(, "Word.Application")
Set wdApp = New Word.Application
wdApp.Documents.Add
wdApp.ActiveDocument.ActiveWindow.Visible = False
' Type the Username
wdApp.Selection.Font.Bold = wdToggle
wdApp.Selection.Font.Size = 13
wdApp.Selection.TypeText Text:=sUser
wdApp.Selection.Font.Size = 11
wdApp.Selection.Font.Bold = wdToggle
wdApp.Selection.TypeParagraph
wdApp.Selection.MoveLeft unit:=wdCharacter, Count:=1
' Assign the selection to Range object
Set rgSel = wdApp.Selection.Range
' Insert the border beneath username
' on Error GoTo appError
' rgSel.Borders(wdBorderBottom).LineStyle = Options.DefaultBorderLineStyle
' rgSel.Borders(wdBorderBottom).LineWidth = wdLineWidth300pt
' rgSel.Borders(wdBorderBottom).Color = Options.DefaultBorderColor
' GoTo borderComplete
' ' Try with wdApp.Selection
'appError:
wdApp.Selection.Borders(wdBorderBottom).LineStyle = wdApp.Options.DefaultBorderLineStyle
wdApp.Selection.Borders(wdBorderBottom).LineWidth = wdLineWidth300pt
wdApp.Selection.Borders(wdBorderBottom).Color = wdApp.Options.DefaultBorderColor
' On Error GoTo 0
'borderComplete:
'
'On Error GoTo errHandler1
'
'' Err.Raise 1000
'
' Move down and add paragraph
wdApp.Selection.MoveDown unit:=wdLine, Count:=1
wdApp.Selection.TypeParagraph
' ========================================
' Loop through array, adding elements if they exist
' ========================================
i = 0
For i = 0 To 6 '<==== probably need to find a way to make dynamic
If arrHeader(1, i) <> "" Then
wdApp.Selection.Font.Bold = wdToggle
wdApp.Selection.TypeText Text:=arrHeader(0, i)
wdApp.Selection.Font.Bold = wdToggle
wdApp.Selection.TypeText Text:=vbTab & arrHeader(1, i)
wdApp.Selection.TypeParagraph
End If
Next
For i = 1 To 3
wdApp.Selection.TypeParagraph
Next
' Format the header
wdApp.Selection.WholeStory
MsgBox True
wdApp.Selection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(1.5), _
Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
MsgBox True
wdApp.Selection.ParagraphFormat.LineSpacing = LinesToPoints(100)
' Format the .ParagraphFormat
wdApp.Selection.ParagraphFormat.LeftIndent = InchesToPoints(1.5)
wdApp.Selection.ParagraphFormat.RightIndent = InchesToPoints(0)
wdApp.Selection.ParagraphFormat.SpaceBefore = 0
wdApp.Selection.ParagraphFormat.SpaceBeforeAuto = False
wdApp.Selection.ParagraphFormat.SpaceAfter = 0
wdApp.Selection.ParagraphFormat.SpaceAfterAuto = False
wdApp.Selection.ParagraphFormat.LineSpacingRule = wdLineSpaceSingle
wdApp.Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft
wdApp.Selection.ParagraphFormat.WidowControl = True
wdApp.Selection.ParagraphFormat.KeepWithNext = False
wdApp.Selection.ParagraphFormat.KeepTogether = False
wdApp.Selection.ParagraphFormat.PageBreakBefore = False
wdApp.Selection.ParagraphFormat.NoLineNumber = False
wdApp.Selection.ParagraphFormat.Hyphenation = True
wdApp.Selection.ParagraphFormat.FirstLineIndent = InchesToPoints(-1.5)
wdApp.Selection.ParagraphFormat.OutlineLevel = wdOutlineLevelBodyText
wdApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = 0
wdApp.Selection.ParagraphFormat.CharacterUnitRightIndent = 0
wdApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = 0
wdApp.Selection.ParagraphFormat.LineUnitBefore = 0
wdApp.Selection.ParagraphFormat.LineUnitAfter = 0
wdApp.Selection.ParagraphFormat.MirrorIndents = False
wdApp.Selection.ParagraphFormat.TextboxTightWrap = wdTightNone
wdApp.Selection.ParagraphFormat.CollapsedByDefault = False
' Format the .PageSetup
wdApp.Selection.PageSetup.LineNumbering.Active = False
wdApp.Selection.PageSetup.Orientation = wdOrientPortrait
wdApp.Selection.PageSetup.TopMargin = InchesToPoints(0.5)
wdApp.Selection.PageSetup.BottomMargin = InchesToPoints(0.5)
wdApp.Selection.PageSetup.LeftMargin = InchesToPoints(0.5)
wdApp.Selection.PageSetup.RightMargin = InchesToPoints(0.5)
wdApp.Selection.PageSetup.Gutter = InchesToPoints(0)
wdApp.Selection.PageSetup.HeaderDistance = InchesToPoints(0.5)
wdApp.Selection.PageSetup.FooterDistance = InchesToPoints(0.5)
wdApp.Selection.PageSetup.PageWidth = InchesToPoints(8.5)
wdApp.Selection.PageSetup.PageHeight = InchesToPoints(11)
wdApp.Selection.PageSetup.FirstPageTray = wdPrinterDefaultBin
wdApp.Selection.PageSetup.OtherPagesTray = wdPrinterDefaultBin
wdApp.Selection.PageSetup.SectionStart = wdSectionNewPage
wdApp.Selection.PageSetup.OddAndEvenPagesHeaderFooter = False
wdApp.Selection.PageSetup.DifferentFirstPageHeaderFooter = False
wdApp.Selection.PageSetup.VerticalAlignment = wdAlignVerticalTop
wdApp.Selection.PageSetup.SuppressEndnotes = False
wdApp.Selection.PageSetup.MirrorMargins = False
wdApp.Selection.PageSetup.TwoPagesOnOne = False
wdApp.Selection.PageSetup.BookFoldPrinting = False
wdApp.Selection.PageSetup.BookFoldRevPrinting = False
wdApp.Selection.PageSetup.BookFoldPrintingSheets = 1
wdApp.Selection.PageSetup.GutterPos = wdGutterPosLeft
' Copy formatted email body of text
Dim wdItemWordEditor As Object
Set wdItemWordEditor = olMI.GetInspector.WordEditor
wdItemWordEditor.Range.Copy
' Paste email body into word doc after header
wdApp.Selection.MoveStart unit:=wdCharacter, Count:=1000000
wdApp.Selection.Paste
' Re-select the whole word doc
wdApp.ActiveDocument.Select
' Remove paragraph spacing
wdApp.Selection.ParagraphFormat.SpaceBefore = 0
wdApp.Selection.ParagraphFormat.SpaceBeforeAuto = False
wdApp.Selection.ParagraphFormat.SpaceAfter = 0
wdApp.Selection.ParagraphFormat.SpaceAfterAuto = False
wdApp.Selection.ParagraphFormat.LineSpacingRule = wdLineSpaceSingle
'================================================================================
' Print/save email as PDF
'================================================================================
' Print doc to PDF
wdApp.ActiveDocument.SaveAs2 FileName:=sFileNamePDF, FileFormat:=wdFormatPDF
' Close doc and close word
wdApp.ActiveDocument.Close savechanges:=wdDoNotSaveChanges
wdApp.Quit savechanges:=wdDoNotSaveChanges
Set wdApp = Nothing
'================================================================================
' Print/save email as PDF
'================================================================================
sPdfRoot = olTempFolder
' Run custom function to merge PDFs and return the final PDF path
sFinalPDF = mergePDF(sPdfRoot)
'================================================================================
' Open the newly created PDF
'================================================================================
' Create shell object
Set Shex = CreateObject("Shell.Application")
' Redundancy IF statement. If function successful, use that path. Otherwise _
use the default path in main sub.
If Not sFinalPDF = "" Then
Shex.Open (sFinalPDF)
Else
Shex.Open (sFileNamePDF)
' This route is less reliable because the merge PDF function selects _
only one of the PDFs in the temp folder as the primary. After _
merge, it deletes the rest of the PDFs in the folder. If it _
selected a primary file other than the sFileNamePDF path, then _
this route will not open the file in Adobe because sFileName PDF _
will not exist.
End If
Exit Sub
'================================================================================
' Error handling
'================================================================================
' General error handling statement
errHandler1:
MsgBox "There was an unexpected error with the macro." & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Message: " & Err.Description
End Sub
Private Function isEmbedded(Att As Outlook.Attachment) As Boolean
' This function determines whether the passed mailitem.attachment is embedded
' https://stackoverflow.com/questions/59075501/ _
find-out-if-an-attachment-is-embedded-or-attached
Dim PropAccessor As Outlook.PropertyAccessor
On Error GoTo outlook_att_IsEmbedded_error
isEmbedded = False
Set PropAccessor = Att.PropertyAccessor
If PropAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E") <> "" Or _
PropAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3713001E") <> "" Then
If PropAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003") = 4 Then
isEmbedded = True
End If
End If
outlook_att_IsEmbedded_exit:
Set PropAccessor = Nothing
Exit Function
outlook_att_IsEmbedded_error:
isEmbedded = False
Resume outlook_att_IsEmbedded_exit
End Function
Private Function GetCurrentItem() As Object
' Purpose: this function returns the active MailItem, whether from the Explorer or Inspector.
'================================================================================
' Initialize variables
'================================================================================
Dim olApp As Outlook.Application
Dim sMailTest As String
Set olApp = Application
'================================================================================
' Initialize variables
'================================================================================
On Error Resume Next
' Determine whether active item is Explorer or Inspector object
Select Case TypeName(olApp.ActiveWindow)
' If explorer item selected, return explorer MailItem
Case "Explorer"
sMailTest = TypeName(olApp.ActiveExplorer.Selection.Item(1))
If Not sMailTest = "MailItem" Then
MsgBox "The selected item is not an Email. Please select another item."
End
End If
Set GetCurrentItem = olApp.ActiveExplorer.Selection.Item(1)
' If inspector item selected, return inspector MailItem
Case "Inspector"
sMailTest = TypeName(olApp.ActiveInspector.CurrentItem)
If Not sMailTest = "MailItem" Then
MsgBox "The selected item is not an Email. Please select another item."
End
End If
Set GetCurrentItem = olApp.ActiveInspector.CurrentItem
End Select
Set olApp = Nothing
End Function
Private Function getEmail(mail As Outlook.MailItem) As String
' Purpose: Return the readable email address of an Outlook user
' Modified version of the following solution: _
https://stackoverflow.com/a/26171979/17312223
'================================================================================
' Declare variables
'================================================================================
Dim PR_SMTP_ADDRESS As String
'================================================================================
' If mail item not selected, exit function
'================================================================================
If mail Is Nothing Then
getEmail = vbNullString
Exit Function
End If
'================================================================================
' Retrieve sender email from mail item
'================================================================================
If mail.SenderEmailType = "EX" Then
Dim sender As Outlook.AddressEntry
Set sender = mail.sender
If Not sender Is Nothing Then
'Now we have an AddressEntry representing the Sender
If sender.AddressEntryUserType = Outlook.OlAddressEntryUserType. _
olExchangeUserAddressEntry Or sender.AddressEntryUserType = _
Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry Then
'Use the ExchangeUser object PrimarySMTPAddress
Dim exchUser As Outlook.ExchangeUser
Set exchUser = sender.GetExchangeUser()
If Not exchUser Is Nothing Then
getEmail = exchUser.PrimarySmtpAddress
Else
getEmail = vbNullString
End If
Else
getEmail = sender.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS)
End If
Else
getEmail = vbNullString
End If
Else
getEmail = mail.SenderEmailAddress
End If
End Function
Private Function mergePDF(sPdfRoot As String)
' Purpose: to merge multiple PDFs together into one.
' Macro influenced by the following solution: _
https://stackoverflow.com/a/51690835/17312223
' If having issues with saving the merged pdf, see the following URL: _
https://stackoverflow.com/questions/71580519/pddoc-save-adobe-acrobat-method-not-working-in-excel-vba
On Error GoTo errHandler1
' ================================================================================
' Declare variables / create objects
' ================================================================================
Dim app As Object
Dim sFile As String
Dim iFwd As Integer
Dim iBwd As Integer
Dim iLArr As Integer
Dim i As Integer
Dim arrayFilePaths() As Variant
ReDim arrayFilePaths(0) ' Enable LBound and UBound calling
Dim primaryDoc As Object
Dim OK As Variant
Dim arrayIndex As Integer
Dim numPages As Integer
Dim numberOfPagesToInsert As Integer
Dim sourceDoc As Object
Dim PDSaveFull As Variant
' Create Adobe app object
'Set app = CreateObject("Acroexch.app")
' Create Adobe PDF object
Set primaryDoc = CreateObject("AcroExch.PDDoc")
' ================================================================================
' Initialize variables
' ================================================================================
' Assign position of ending slash to variable
iFwd = InStrRev(sPdfRoot, "/") ' Forward slash
iBwd = InStrRev(sPdfRoot, "\") ' Backward slash
' Check for ending slash existence
If Not iFwd > 0 Or Not iBwd > 0 Then
' If no ending slash, add
sPdfRoot = sPdfRoot & "\"
End If
' ================================================================================
' Loop through root, assigning PDF files to array
' ================================================================================
' Assign directory and wildcard to search for within
sFile = Dir(sPdfRoot & "*.pdf*")
' Get lowest boundary of array dimension
iLArr = LBound(arrayFilePaths)
' Assign lower array boundary to beginning iteration counter
i = iLArr
' Loop through the entire array
Do While sFile <> ""
' Add additional space to array variable
ReDim Preserve arrayFilePaths(iLArr To i)
' Assign the iteration file to the new array space
arrayFilePaths(i) = sPdfRoot & sFile
' Iterate counter by 1
i = i + 1
' Iterate to next file in directory
sFile = Dir()
Loop
i = 0
' Set the primary PDF document
OK = primaryDoc.Open(arrayFilePaths(0))
Debug.Print "PRIMARY DOC OPENED & PDDOC SET: " & OK
' Return the path of primary document
mergePDF = arrayFilePaths(0)
' ================================================================================
' Loop through non-primary PDFs
' ================================================================================
For arrayIndex = 1 To UBound(arrayFilePaths)
' Get number of pages of primary PDF _
(minus one bc "insertPages" index starts at 0)
numPages = primaryDoc.GetNumPages() - 1
'Debug.Print "Number of pages in primary doc = " & numPages
' Set iteration PDF to be merged into primary
Set sourceDoc = CreateObject("AcroExch.PDDoc")
' Open iteration PDF
OK = sourceDoc.Open(arrayFilePaths(arrayIndex))
'Debug.Print "source doc = " & arrayFilePaths(arrayIndex)
' Get number of pages of iteration PDF
Debug.Print "SOURCE DOC OPENED & PDDOC SET: " & OK
numberOfPagesToInsert = sourceDoc.GetNumPages
'Debug.Print "# Pages to insert = " & numberOfPagesToInsert
' Insert iteration PDF into primary document
OK = primaryDoc.InsertPages _
(numPages, sourceDoc, 0, numberOfPagesToInsert, False)
Debug.Print _
"============================================" & vbCrLf & _
"# total pages: " & numPages + 1 & vbCrLf & _
"source doc name: " & sourceDoc.GetFileName() & vbCrLf & _
"# pages to insert: " & numberOfPagesToInsert
Debug.Print "PAGES INSERTED SUCCESSFULLY: " & OK
' Save primary PDF that now contains iteration PDF
OK = primaryDoc.Save(PDSaveFull, mergePDF) 'arrayFilePaths(0)
Debug.Print "PRIMARYDOC SAVED PROPERLY: " & OK
' Close the iteration document
OK = sourceDoc.Close
' Delete the iteration document (since it is merged into primary)
Kill (arrayFilePaths(arrayIndex))
' Clear iteration object
Set sourceDoc = Nothing
Next arrayIndex
' ================================================================================
' Clear objects/variables
' ================================================================================
Set primaryDoc = Nothing
'app.Exit
'Set app = Nothing
' ================================================================================
' Error handling
' ================================================================================
Exit Function
errHandler1:
Debug.Print "###########################################################" & _
vbCrLf & "There was an error within the PDF portion of the macro." _
& vbCrLf & "Error #: " & Err.Number & "Error Msg: " & Err.Description & _
vbCrLf & "###########################################################"
' ================================================================================
' End sub
' ================================================================================
End Function

Related

MS Word populate text after is inserted via VBA form

I have created word macro enabled template.
At opening form pops-up and user can fill in form. After pressing OK bookmarks inside document are updated and shown.
What I need is to populate entered values trough entire document on multiple locations. I have tried cross-referencing bookmarks but they are not updated with values entered in form.
image of opening form
Private Sub cancelBut_Click()
stInfo.Hide
End Sub
Private Sub Label11_Click()
End Sub
Private Sub OKbut_Click()
Dim katcest As Range
Set katcest = ActiveDocument.Bookmarks("katcest").Range
katcest.Text = Me.TextBox1.Value
Dim katopcina As Range
Set katopcina = ActiveDocument.Bookmarks("katopcina").Range
katopcina.Text = Me.TextBox2.Value
Dim zkcest As Range
Set zkcest = ActiveDocument.Bookmarks("zkcest").Range
zkcest.Text = Me.TextBox3.Value
Dim zkopcina As Range
Set zkopcina = ActiveDocument.Bookmarks("zkopcina").Range
zkopcina.Text = Me.TextBox4.Value
Dim zkulozak As Range
Set zkulozak = ActiveDocument.Bookmarks("zkulozak").Range
zkulozak.Text = Me.TextBox5.Value
Dim povrsina As Range
Set povrsina = ActiveDocument.Bookmarks("povrsina").Range
povrsina.Text = Me.TextBox6.Value
Dim vlasnik As Range
Set vlasnik = ActiveDocument.Bookmarks("vlasnik").Range
vlasnik.Text = Me.TextBox7.Value
Dim vladresa As Range
Set vladresa = ActiveDocument.Bookmarks("vladresa").Range
vladresa.Text = Me.TextBox8.Value
Dim datocevida As Range
Set datocevida = ActiveDocument.Bookmarks("datocevida").Range
datocevida.Text = Me.TextBox9.Value
Dim klasa As Range
Set klasa = ActiveDocument.Bookmarks("klasa").Range
klasa.Text = Me.TextBox10.Value
Dim urbroj As Range
Set urbroj = ActiveDocument.Bookmarks("urbroj").Range
urbroj.Text = Me.TextBox11.Value
Me.Repaint
Dim strDocName As String
Dim intPos As Integer
' Find position of extension in file name
strDocName = ""
intPos = InStrRev(strDocName, ".")
If intPos = 0 Then
' If the document has not yet been saved
' Ask the user to provide a file name
strDocName = InputBox("Upisi naziv " & _
"vaseg dokumenta.")
Else
' Strip off extension and add ".txt" extension
strDocName = Left(strDocName, intPos - 1)
strDocName = strDocName & ".docx"
End If
' Save file with new extension
ActiveDocument.SaveAs2 FileName:=strDocName, _
FileFormat:=wdFormatDocumentDefault
stInfo.Hide
infoForm.Show
End Sub

Outlook - VBA set signature to new Email ... so the signature can be changed via menu

I wrote a script where I add a signature from an htm file in the appData ... signature folder to a newly opened email.
My question is - how do i modify this VBA script to add that signature in a way so Outlook knows its a signature and the signature might be changed by a user via gui.
I assume it may have something to do with setting a "_MailAutoSig" bookmark, is that right?
Script looks like this and works so far:
Dim WithEvents m_objMail As Outlook.MailItem
Dim LODGIT_SUBJECT_IDENTIFIERS() As String
Private Sub Application_ItemLoad(ByVal Item As Object)
'MsgBox "Application_ItemLoad"
Select Case Item.Class
Case olMail
Set m_objMail = Item
End Select
End Sub
Private Sub m_objMail_Open(Cancel As Boolean)
'string array containing lodgit email subject identifiers (beginning string!!! of email subject)
LODGIT_SUBJECT_IDENTIFIERS = Split("Angebot von Bödele Alpenhotel,Angebot von,bestätigt Ihre Reservierung,Rechnung Nr.,Stornogutschrift für die Rechnung,Ausstehende Zahlung", ",")
Dim Application As Object
Dim oOutApp As Object, oOutMail As Object
Dim strbody As String, FixedHtmlBody As String
Dim Ret
Set Application = CreateObject("Outlook.Application")
'Change only Mysig.htm to the name of your signature
' C:\Users\nicole\AppData\Roaming\Microsoft\Signatures
Ret = Environ("appdata") & _
"\Microsoft\Signatures\AH Andrea kurz.htm"
If Ret = False Then Exit Sub
'~~> Use the function to fix image paths in the htm file
FixedHtmlBody = FixHtmlBody(Ret)
'CHECK FOR LODGIT IDENTIFIER
If myInStr(m_objMail.Subject, LODGIT_SUBJECT_IDENTIFIERS()) Then
Debug.Print "E-Mail as from Lodgit identified"
Dim str As String
Dim a As Object
str = Replace(m_objMail.Body, vbCrLf, "<br>")
str = Replace(str, vbNewLine, "<br>")
m_objMail.HTMLBody = "<html><body><span style='font-size:11.0pt;font-family:""Times New Roman"" '>" & str & "</span>" & FixedHtmlBody & "</body></html>"
End If
End Sub
'~~> Function to fix image paths in Signature .htm Files
Function FixHtmlBody(r As Variant) As String
Dim FullPath As String, filename As String
Dim FilenameWithoutExtn As String
Dim foldername As String
Dim MyData As String
'~~> Read the html file as text file in a string variable
Open r For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
'~~> Get File Name from path
filename = GetFilenameFromPath(r)
'~~> Get File Name without extension
FilenameWithoutExtn = Left(filename, (InStrRev(filename, ".", -1, vbTextCompare) - 1))
'~~> Get the foldername where the images are stored
foldername = FilenameWithoutExtn & "-Dateien"
'~~> Full Path of Folder
FullPath = Left(r, InStrRev(r, "\")) & foldername
'~~> To cater for spaces in signature file name
'FullPath = Replace(FullPath, " ", "%20")
'~~> Replace incomplete path with full Path
FixHtmlBody = Replace(MyData, "AH%20Andrea%20kurz-Dateien", FullPath)
'FixHtmlBody = Replace(MyData, foldername, FullPath)
End Function
'~~> Gets File Name from path
Public Function GetFilenameFromPath(ByVal strPath As String) As String
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then _
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End Function
'check if str contains on of the elements of a str array
Public Function myInStr(myString As String, a() As String) As Boolean
For Each elem In a
If InStr(1, myString, elem, vbTextCompare) <> 0 Then
myInStr = True
Exit Function
End If
Next
myInStr = False
End Function
Outlook looks for the "_MailAutoSig" bookmark. This needs to be done with Word Object Model, not by setting the HTMLBody property. Something along the lines:
wdStory = 6
wdMove = 0
Set objBkm = Nothing
Set objDoc = Inspector.WordEditor
Set objSel = objDoc.Application.Selection
'remember the cursor position
set cursorRange = objDoc.Range
cursorRange.Start = objSel.Start
cursorRange.End = objSel.End
If objDoc.Bookmarks.Exists("_MailAutoSig") Then
'replace old signature
Debug.Print "old signature found"
set objBkm = objDoc.Bookmarks("_MailAutoSig")
objBkm.Select
objDoc.Windows(1).Selection.Delete
ElseIf objDoc.Bookmarks.Exists("_MailOriginal") Then
' is there the original email? (_MailOriginal)
set objBkm = objDoc.Bookmarks("_MailOriginal")
objSel.Start = objBkm.Start-2 'give room for the line break before. It includes the line
objSel.End = objBkm.Start-2
Else
'insert at the end of the email
objSel.EndOf wdStory, wdMove
End If
'start bookmark
set bkmStart = objDoc.Bookmarks.Add("_tempStart", objSel.Range)
'end bookmark
set bkmEnd = objDoc.Bookmarks.Add("_tempEnd", objSel.Range)
bkmEnd.End = bkmEnd.End + 1
bkmEnd.Start = bkmEnd.Start + 1
objSel.Text = " "
set objBkm = objDoc.Bookmarks.Add("_MailAutoSig", bkmStart.Range)
objBkm.Range.insertFile "c:\Users\<user>\AppData\Roaming\Microsoft\Signatures\test.htm", , false, false, false
objBkm.Range.InsertParagraphBefore
objBkm.End = bkmEnd.Start - 1 'since we added 1 above for bkmEnd
objSel.Start = cursorRange.Start
objSel.End = cursorRange.End
bkmStart.Delete
bkmEnd.Delete

not able to copy data from PDF file

I am able to open pdf doc from attachments from mail. Now I want to copy its content. kindly provide code to select all and copy. Below is the code and I have mentioned where I need help.
I am able to open pdf doc from attachments from mail. Now I want to copy its content. kindly provide code to select all and copy. Below is the code and I have mentioned where I need help.
Sub ExtractFirstUnreadEmailDetails()
Dim oOlAp As Object, oOlns As Object, oOlInb As Object
Dim oOlItm As Object
Dim objAtt As Outlook.Attachment
'On Error Resume Next
'~~> Outlook Variables for email
Dim eSender As String, dtRecvd As String, dtSent As String
Dim sSubj As String, sMsg As String
Dim AttchType As String
'~~> Get Outlook instance
Set oOlAp = GetObject(, "Outlook.application")
Set oOlns = oOlAp.GetNamespace("MAPI")
Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)
'~~> Check if there are any actual unread emails 'apurv
'If oOlInb.Items.Restrict("[UnRead] = True").Count = 0 Then 'apurv
' MsgBox "NO Unread Email In Inbox" 'apurv
' Exit Sub 'apurv
' End If 'apurv
'~~> Store the relevant info in the variables
'For Each oOlItm In oOlInb.Items.Restrict("[UnRead] = True")
For Each oOlItm In oOlInb.Items
eSender = oOlItm.SenderEmailAddress
dtRecvd = oOlItm.ReceivedTime
dtSent = oOlItm.CreationTime
sSubj = oOlItm.Subject
sMsg = oOlItm.Body
ToAddress = oOlItm.To
i = ThisWorkbook.ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row
Range("c" & (i + 1)).Value = eSender
Range("B" & (i + 1)).Value = dtRecvd
'range("c"&(i+1)).Value=dtSent
Range("E" & (i + 1)).Value = sSubj
Range("F" & (i + 1)).Value = sMsg
Range("D" & (i + 1)).Value = ToAddress
If oOlItm.Attachments.Count <> 0 Then
temp = ""
For Each oOlAtch In oOlItm.Attachments
temp = temp & "//" & oOlAtch.Filename
Next
Range("G" & (i + 1)).Value = temp
End If
If oOlItm.Attachments.Count <> 0 Then
temp = ""
For Each oOlAtch In oOlItm.Attachments
If InStr(1, UCase(oOlAtch.Filename), "PDF", vbTextCompare) > 1 Then
oOlAtch.SaveAsFile "D:\Users\apawar\Desktop\Attachments\" & oOlAtch.Filename
Shell "Explorer.exe /e,D:\Users\apawar\Desktop\Attachments\" & oOlAtch.Filename, vbNormalFocus
'NEED HELP HERE......Need to copy all data from pdf doc from 1st page
End If
Next
Range("G" & (i + 1)).Value = temp
End If
Next
MsgBox ("Down loaded successufully")
End Sub
You should probably get Acrobat, and this will be much easier. Or, convert the PDF into a text file, simply by saving it, and import the text into Excel.

VBA code to open all excel files in a folder

I was working with a vba and I'm trying to open all excel files in a folder (about 8-10) based on cell values. I was wondering if this is the right approach to opening it, it keeps giving me syntax error where I wrote the directory. and when I rewrote that section, the vba only shot out the msgbox which meant it had to have looped and did something right? but didn't open any files. Any information will help. Thank you guys so much for taking the time to help me in any way.
Sub OpenFiles()
Dim search As Worksheet
Dim customer As Range
Dim customerfolder As Range
Dim QualityHUB As Workbook
'setting variable references
Set QualityHUB = ThisWorkbook
Set search = Worksheets("Search")
Set customer = Worksheets("Search").Range("$D$1")
Set customerfolder = Worksheets("Search").Range("$D$3")
With QualityHUB
If IsEmpty((customer)) And IsEmpty((customerfolder)) Then
MsgBox "Please Fill out Customer Information and search again"
Exit Sub
End If
End With
With QualityHUB
Dim MyFolder As String
Dim MyFile As String
Dim Directory As String
Directory = "O:\LAYOUT DATA\" & customer & "\" & customerfolder"
MyFile = Dir(Directory & "*.xlsx")
Do While MyFile <> ""
Workbooks.Open Filename:=MyFile
MyFile = Dir()
Loop
MsgBox "Files Open for " + customerfolder + " complete"
End With
End Sub
This worked for me perfectly
Sub OpenFiles()
Dim search As Worksheet
Dim customer As Range
Dim customerfolder As Range
Dim QualityHUB As Workbook
'setting variable references
Set QualityHUB = ThisWorkbook
Set search = Worksheets("Search")
Set customer = Worksheets("Search").Range("$D$1")
Set customerfolder = Worksheets("Search").Range("$D$3")
With QualityHUB
If IsEmpty((customer)) And IsEmpty((customerfolder)) Then
MsgBox "Please Fill out Customer Information and search again"
Exit Sub
End If
End With
With QualityHUB
Dim MyFolder As String
Dim MyFile As String
Dim Directory As String
Directory = "O:\LAYOUT DATA\" & customer & "\" & customerfolder & "\"
MyFile = Dir(Directory & "*.xlsx")
Do While MyFile <> ""
Workbooks.Open Filename:=Directory & MyFile
MyFile = Dir()
Loop
MsgBox "Files Open for " + customerfolder + " complete"
End With
End Sub
one of the issue was, you had to write
Workbooks.Open Filename:=Directory & MyFile
instead of
Workbooks.Open Filename:=MyFile
Corrected some issues with your code and cleaned it up, give this a try. I think the big issue was you had an extra double-quote, and you missing the ending \ in the Directory line:
Sub OpenFiles()
Dim QualityHUB As Workbook
Dim search As Worksheet
Dim customer As String
Dim customerfolder As String
Dim Directory As String
Dim MyFile As String
'setting variable references
Set QualityHUB = ThisWorkbook
Set search = QualityHUB.Worksheets("Search")
customer = search.Range("$D$1").Value
customerfolder = search.Range("$D$3").Value
If Len(Trim(customer)) = 0 Or Len(Trim(customerfolder)) = 0 Then
MsgBox "Please Fill out Customer Information and search again"
Exit Sub
End If
Directory = "O:\LAYOUT DATA\" & customer & "\" & customerfolder & "\" '<--- This requires the ending \
MyFile = Dir(Directory & "*.xlsx")
Do While Len(MyFile) > 0
Workbooks.Open Filename:=Directory & MyFile
MyFile = Dir()
Loop
MsgBox "Files Open for " + customerfolder + " complete"
End Sub
I found this code online and it will open all the excel files in a folder, you can adapt the code to apply a function to the workbook, once it is open.
Option Explicit
Type FoundFileInfo
sPath As String
sName As String
End Type
Sub find()
Dim iFilesNum As Integer
Dim iCount As Integer
Dim recMyFiles() As FoundFileInfo
Dim blFilesFound As Boolean
blFilesFound = FindFiles("G:\LOCATION OF FOLDER HERE\", _
recMyFiles, iFilesNum, "*.xlsx", True)
End Sub
Function FindFiles(ByVal sPath As String, _
ByRef recFoundFiles() As FoundFileInfo, _
ByRef iFilesFound As Integer, _
Optional ByVal sFileSpec As String = "*.*", _
Optional ByVal blIncludeSubFolders As Boolean = False) As Boolean
Dim iCount As Integer '* Multipurpose counter
Dim sFileName As String '* Found file name
Dim wbResults, file, WS_Count, i, gcell, col, finRow, wbCodeBook As Workbook, lCount, name, looper
Dim WorksheetExists
Set wbCodeBook = ThisWorkbook
'*
'* FileSystem objects
Dim oFileSystem As Object, _
oParentFolder As Object, _
oFolder As Object, _
oFile As Object
Set oFileSystem = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set oParentFolder = oFileSystem.GetFolder(sPath)
If oParentFolder Is Nothing Then
FindFiles = False
On Error GoTo 0
Set oParentFolder = Nothing
Set oFileSystem = Nothing
Exit Function
End If
sPath = IIf(Right(sPath, 1) = "\", sPath, sPath & "\")
'*
'* Find files
sFileName = Dir(sPath & sFileSpec, vbNormal)
If sFileName <> "" Then
For Each oFile In oParentFolder.Files
If LCase(oFile.name) Like LCase(sFileSpec) Then
iCount = UBound(recFoundFiles)
iCount = iCount + 1
ReDim Preserve recFoundFiles(1 To iCount)
file = sPath & oFile.name
name = oFile.name
End If
On Error GoTo nextfile:
Set wbResults = Workbooks.Open(Filename:=file, UpdateLinks:=0)
''insert your code here
wbResults.Close SaveChanges:=False
nextfile:
Next oFile
Set oFile = Nothing '* Although it is nothing
End If
If blIncludeSubFolders Then
'*
'* Select next sub-forbers
For Each oFolder In oParentFolder.SubFolders
FindFiles oFolder.path, recFoundFiles, iFilesFound, sFileSpec, blIncludeSubFolders
Next
End If
FindFiles = UBound(recFoundFiles) > 0
iFilesFound = UBound(recFoundFiles)
On Error GoTo 0
'*
'* Clean-up
Set oFolder = Nothing '* Although it is nothing
Set oParentFolder = Nothing
Set oFileSystem = Nothing
End Function
Function SSCGetColumnCodeFromIndex(colIndex As Variant) As String
Dim tstr As String
Dim prefixInt As Integer
Dim suffixInt As Integer
prefixInt = Int(colIndex / 26)
suffixInt = colIndex Mod 26
If prefixInt = 0 Then
tstr = ""
Else
prefixInt = prefixInt - 1
tstr = Chr(65 + prefixInt)
End If
tstr = tstr + Chr(65 + suffixInt)
SSCGetColumnCodeFromIndex = tstr
End Function
Function GetColNum(oSheet As Worksheet, name As String)
Dim Endrow_Col, i
'For loop to get the column number of name
Endrow_Col = oSheet.Range("A1").End(xlToRight).Column
oSheet.Select
oSheet.Range("A1").Select
For i = 0 To Endrow_Col - 1 Step 1
If ActiveCell.Value <> name Then
ActiveCell.Offset(0, 1).Select
ElseIf ActiveCell.Value = name Then
GetColNum = ActiveCell.Column
Exit For
End If
Next i
End Function
Function ShDel(name As String)
End If
End Function

Read a CSV file and list of folders and then compare in VB

What I am trying to achieve is I currently have a (main) folder filled with many Sub-folders and these sometimes get drag & dropped into another Sub-folder by accident.
I have an CSV file containing all the names of the current (main) folder list as it should stand and I want to check this against the current version of Sub-folders found in the (main) folder and output a message box with the results of matching files and missing files.
This is the code I have got so far although I am unsure how to check the list of folders against the CSV file.
Read data from an CSV file.
'Holds Data from CSV file
Dim arrValue As String()
'create a new TextFieldParser and opens the file
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Users\USERNAME\Dropbox (Personal)\IT\jobs.csv")
'Define the TextField type and delimiter
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
While Not MyReader.EndOfData
Dim arrCurrentRow As String() = MyReader.ReadFields()
If arrValue Is Nothing Then
ReDim Preserve arrValue(0)
arrValue(0) = arrCurrentRow(0)
Else
ReDim Preserve arrValue(arrValue.Length)
arrValue((arrValue.Length - 1)) = arrCurrentRow(0)
End If
End While
Read list of folders
'check against the Clients folder
Set w = WScript.CreateObject("WScript.Shell")
w.Popup ShowFolders("C:\Users\USERNAME\Dropbox (Innovation PS)\Clients")
Function ShowFolders(folderName)
'Setting Variables
Dim fs, f, f1, fc, s
'holds folder name
s = ""
'Obtain folder Object
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(folderName)
'Obtain SubFolders collection within folder
Set fc = f.SubFolders
'Examine each item in the collection
For Each f1 in fc
s = s & f1.name
s = s & (Chr(13) & Chr(10)) ' Chr(13) & Chr(10) = Carriage return–linefeed combination
Next
ShowFolders = s
End Function
'See if it matches the .CSV file
Thank you in advance. (Also if you could include comments it would be appreciated)
Run this script to get a base line, it wil create a spreadsheet of the folders files and properties, Then runt it again copy the sheet in to the baseline work bbok and do a vlookup. You could also use this as a base line to create a csv and compare the it that way. Not exactly waht you are looking for but it is a workable solution
Const ForReading = 1, ForWriting = 2, Forappending = 8
'Option Explicit
'DIM Objects
'Dim variabbles
Dim folderspec
'Dim
DIM arrBlk(3)
DIM arrFLN(3)
DIM arrInfo(3)
Set objXL = Wscript.CreateObject("Excel.Application")
Set ofso = CreateObject("Scripting.FileSystemObject")
folderspec = InputBox("Please enter the path", "FileList", " ")
If folderspec = "" Then
' if cancel is selected quit the program
wscript.quit
ElseIf folderspec = " " Then
' if nothing is entered give a warning message ang quit the program
msgbox "No Directory has been seleted " & vbCrLf
wscript.quit
End If
intRow = 2
buildsheet() 'Build the XLS spreadsheet
'folderspec ="C:\_epas_5.0\Web_Server\ASP"
'folderspec ="C:\_epas_5.0\Web_Server\COM+ Source"
strFldrCmp = folderspec
Set root = ofso.GetFolder(folderspec)
ShowFileList(root)
For Each oFolder in root.subfolders
walkfolder oFolder
Next
Sub walkfolder(f)
ShowFileList(f)
For Each sf in f.subfolders
walkfolder sf
Next
End Sub
Function ShowFileList(folderspec)
Dim oFolder
Dim oFiles
Dim oFile
Set oFolder = ofso.GetFolder(folderspec)
' Wscript.echo oFolder.name
Set oFiles = oFolder.Files
' If IsEmpty(oFiles) Then Wscript.echo oFolder.name
'i = 0
For Each oFile in oFiles
i = 1 + i
'If i < 1 Then
'Wscript.echo oFolder.name,i
'End If
Next
If i < 1 Then
Wscript.echo oFolder.name & " Null"
ReDim arrB(3)
'strPath = Replace(oFolder.path,strFldrCmp,"", 1 ,1 ,vbTextCompare)
arrB(0) = "\" & Trim(oFolder.Name) 'oFolder.path
arrB(1) = ""
arrB(2) = ""
arrB(3) = ""
AddLineToXLS(arrB)
End If
For Each oFile in oFiles
ReDim arrB(3)
srtfldr = oFolder.path
' MsgBox srtfldr& " " & strFldrCmp
'strPath = Replace(srtfldr,strFldrCmp,"", 1 ,1 ,vbTextCompare)
strPath = Replace(oFolder.path,strFldrCmp,"", 1 ,1 ,vbTextCompare)
'strPath = Replace("C:\_5Test\Web_Server\ASP\app\admin","C:\_5Test\Web_Server\ASP","",,,vbTestCompare)
arrB(0) = Trim(strPath) 'oFolder.path
arrB(1) = Trim(oFile.name)
arrB(2) = Trim(oFile.Size)
arrB(3) = Trim(oFile.DateLastModified)
If LCase(ofso.GetExtensionName(oFile)) <> "scc" Then 'skip VSS .scc files
AddLineToXLS(arrB)
End If
Next
End Function
Function buildsheet
intRow = 1
objXL.Visible = True
objXL.WorkBooks.Add
'** Set Row Height
objXL.Rows(1).RowHeight = 17
'** Set Column widths
objXL.Columns(1).ColumnWidth = 40.14
objXL.Columns(2).ColumnWidth = 33.14
objXL.Columns(3).ColumnWidth = 15
objXL.Columns(4).ColumnWidth = 23
objXL.Columns(5).ColumnWidth = 23
objXL.Columns(6).ColumnWidth = 23
'** Set Cell Format for Column Titles ***
objXL.Range("A1:F1").Select
objXL.Selection.Font.Bold = True
' objXL.Selection.Font.Size = 8
objXL.Selection.Interior.ColorIndex = 15
objXL.Selection.Interior.Pattern = 1 'xlSolid
objXL.Selection.Font.ColorIndex = 1
objXL.Selection.WrapText = True
objXL.Columns("A:T").Select
objXL.Columns.Font.Size = 8
objXL.Selection.HorizontalAlignment = 1 'xlCenter
objXL.Columns("C:C").Select
objXL.Selection.NumberFormat = "#,###0"
objXL.Columns("D:D").Select
objXL.Selection.NumberFormat = "m/d/yy h:mm AM/PM"
'*** Set Column Titles ***
Dim arrA(3)
arrA(0)= "File Path"
arrA(1) = "File Name"
arrA(2) = "Size(bytes)"
arrA(3) = "Modified Date/Time"
AddLineToXLS(arrA)
End Function
Function AddLineToXLS(r)' Writes a line to the spreadsheet recieves an array as input
objXL.Cells(intRow, 1).Value = r(0)
objXL.Cells(intRow, 2).Value = r(1)
objXL.Cells(intRow, 3).Value = r(2)
objXL.Cells(intRow, 4).Value = r(3)
' MsgBox r(3)
'objXL.Cells(intRow, 5).Value = r(4)
'objXL.Cells(intRow, 6).Value = r(5)
' objXL.Cells(intRow, 4).Value = r(3)
intRow = intRow + 1
objXL.Cells(1, 1).Select
End Function