not able to copy data from PDF file - vba

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.

Related

Qualified Reference to Word Enumerations

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

Open text file only once in excel vba

I have below code which prints text from a column but open a text file many times instead of once. Please let me know what is the wrong.
When I run sub in Visual Basic debug mode, it open text file only once. But I am calling this macro after another macro and that time it is opening (same) text file many times.
Sub createdevtest()
Dim filename As String, lineText As String
Dim data As Range
Dim myrng As Range, i, j
' filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"
filename = ThisWorkbook.Path & "\devtest" & ".txt"
Open filename For Output As #1
Dim LastRow As Long
'Find the last non-blank cell in column A(1)
LastRow = Cells(Rows.count, 1).End(xlUp).Row
Range("B4:B" & LastRow).Select
Set myrng = Selection
For i = 1 To myrng.Rows.count
For j = 1 To myrng.Columns.count
lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
Next j
Print #1, lineText
Next i
Close #1
Range("B4").Select
' open devtest
'Shell "explorer.exe" & " " & ThisWorkbook.Path, vbNormalFocus
filename = Shell("Notepad.exe " & filename, vbNormalFocus)
End Sub
Thanks #Luuklag. I had tried to figure out on my own but no success. After your comment, just went thru code again and got clue.
Below is the correct code where I have called one of the macro (devtest1) which contains above text file creation macro (createdevtest). Before correction I was calling macro in function instead of Sub, so it was looping again and opening txt file many times.
' macro to select folder and list files
Sub GetFileNames_devtest()
Set Folder = Application.FileDialog(msoFileDialogFolderPicker)
If Folder.Show <> -1 Then Exit Sub
xDir = Folder.SelectedItems(1)
Call ListFilesInFolder(xDir, True)
' call devtest: corrected to call macro at right place
devtest1
End Sub
Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)
Dim xFileSystemObject As Object
Dim xFolder As Object
Dim xSubFolder As Object
Dim xFile As Object
Dim rowIndex As Long
Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set xFolder = xFileSystemObject.GetFolder(xFolderName)
rowIndex = Application.ActiveSheet.Range("A65536").End(xlUp).Row + 1
For Each xFile In xFolder.Files
Application.ActiveSheet.Cells(rowIndex, 1).Formula = xFile.Name
rowIndex = rowIndex + 1
Next xFile
If xIsSubfolders Then
For Each xSubFolder In xFolder.SubFolders
ListFilesInFolder xSubFolder.Path, True
Next xSubFolder
End If
Set xFile = Nothing
Set xFolder = Nothing
Set xFileSystemObject = Nothing
'' Was calling wrongly macro here
End Sub
Function GetFileOwner(ByVal xPath As String, ByVal xName As String)
Dim xFolder As Object
Dim xFolderItem As Object
Dim xShell As Object
xName = StrConv(xName, vbUnicode)
xPath = StrConv(xPath, vbUnicode)
Set xShell = CreateObject("Shell.Application")
Set xFolder = xShell.Namespace(StrConv(xPath, vbFromUnicode))
If Not xFolder Is Nothing Then
Set xFolderItem = xFolder.ParseName(StrConv(xName, vbFromUnicode))
End If
If Not xFolderItem Is Nothing Then
GetFileOwner = xFolder.GetDetailsOf(xFolderItem, 8)
Else
GetFileOwner = ""
End If
Set xShell = Nothing
Set xFolder = Nothing
Set xFolderItem = Nothing
End Function
End Function

Create a loop until all cells have been used by script

I don't really know how to program but I have compiled a few scripts to achieve nearly what I want, but I have failed at the last step.
The script opens a .txt file from a file directory in, cell B2, sheet 2, and copies its contents into excel (as well as a notepad which I don't care about).
However, I have 120 file directories I want to do this for. At the moment my script just takes the directory from cell B2, I have the rest of the 119 directories below it in the B column, I run the script and delete the row and repeat, which is a bit painstaking.
I would just like the script to run through all 120 files in the B column automatically. Any help appreciated!
Option Explicit
Sub ReadTxtFile()
Dim start As Date
start = Now
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oFS As Object
Dim filePath As String
'''''Assign the Workbook File Name along with its Path
filePath = Worksheets("Sheet2").Range("B2").Value
MsgBox Worksheets("Sheet2").Range("B2").Value
Dim arr(100000) As String
Dim i As Long
i = 0
If oFSO.FileExists(filePath) Then
On Error GoTo Err
Set oFS = oFSO.OpenTextFile(filePath)
Do While Not oFS.AtEndOfStream
arr(i) = oFS.ReadLine
i = i + 1
Loop
oFS.Close
Else
MsgBox "The file path is invalid.", vbCritical, vbNullString
Exit Sub
End If
For i = LBound(arr) To UBound(arr)
If InStr(1, arr(i), "Transmission", vbTextCompare) Then
'Declare variables for the new output file
Dim sOutputFileNameAndPath As String
Dim FN As Integer
sOutputFileNameAndPath = "C:\Users\nfraser\Documents\test\second.txt"
FN = FreeFile
'Open new output file
Open sOutputFileNameAndPath For Output As #FN
'While 'end of report' has not been found,
'keep looping to print out contents starting from 'report'
Do While InStr(1, arr(i), "Ancillary", vbTextCompare) = 0
Debug.Print i + 1, arr(i)
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)
'Print into new output file
Print #FN, i + 1 & " " & arr(i)
'increment count
i = i + 1
Loop
'Print out the 'end of report' line as well
Debug.Print i + 1, arr(i)
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)
'Print 'end of report' line into new output file as well
Print #FN, i + 1 & " " & arr(i)
'close the new output file
Close #FN
'exit the 'For..Next' structure since 'end of report' has been found
Exit For
End If
Next
Debug.Print DateDiff("s", start, Now)
Exit Sub
Err:
MsgBox "Error while reading the file.", vbCritical, vbNullString
oFS.Close
Exit Sub
End Sub
You can add a for... each loop, looping through all cells in your current selection. Here's the pattern:
Dim cCell as Range
For Each cCell in Selection
'do stuff
Next cCell
Now, since you change selections throughout your code, you have to store the selection at the onset into another variable, e.g. originalSelection and then loop through the cells in originalSelection. Otherwise, your selection will change during execution.
Adapting it to your code, we end up with the following... Please note: I broke your code into two methods---ReadTxtFiles and copyTo; the ReadTxtFile() sub was getting way too long.
Option Explicit
Sub ReadTxtFiles()
Dim start As Date
start = Now
Dim oFS As Object
Dim inputFilePath As String
Dim outputFilePath As String
Dim outputDirectory As String
outputDirectory = "C:\Users\nfraser\Documents\test\"
'''''Assign the Workbook File Name along with its Path
Dim originalSelection As Range
Dim cCell As Range
Dim i As Integer
Set originalSelection = Selection
For Each cCell In originalSelection
inputFilePath = cCell.Value
outputFilePath = outputDirectory & i & ".txt"
copyTo inputFilePath, outputFilePath
Next cCell
Debug.Print DateDiff("s", start, Now)
End Sub
Sub copyTo(inputPath As String, outputPath As String)
Dim arr(100000) As String
Dim i As Long
Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject") 'late binding
Dim oFS As Object
i = 0
If oFSO.FileExists(inputPath) Then
On Error GoTo Err 'ensure oFS gets closed
Set oFS = oFSO.OpenTextFile(inputPath)
'read file contents into array
Do While Not oFS.AtEndOfStream
arr(i) = oFS.ReadLine
i = i + 1
Loop
'close
oFS.Close
Else 'file didn't exist
MsgBox "The file path is invalid.", vbCritical, vbNullString
Exit Sub
End If
For i = LBound(arr) To UBound(arr)
If InStr(1, arr(i), "Transmission", vbTextCompare) Then
'Declare variables for the new output file
Dim FN As Integer
FN = FreeFile
'Open new output file
Open outputPath For Output As #FN
'While 'end of report' has not been found,
'keep looping to print out contents starting from 'report'
Do While InStr(1, arr(i), "Ancillary", vbTextCompare) = 0
Debug.Print i + 1, arr(i)
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)
'Print into new output file
Print #FN, i + 1 & " " & arr(i)
'increment count
i = i + 1
Loop
'Print out the 'end of report' line as well
Debug.Print i + 1, arr(i)
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)
'Print 'end of report' line into new output file as well
Print #FN, i + 1 & " " & arr(i)
'close the new output file
Close #FN
'exit the 'For..Next' structure since 'end of report' has been found
Exit For
End If
Next
Exit Sub
Err:
MsgBox "Error while reading the file.", vbCritical, vbNullString
oFS.Close
Exit Sub
End Sub
For a quick action, Try this:
Change this line:
filePath = Worksheets("Sheet2").Range("B2").Value
Into a loop
Dim v As Variant, filepath As String
For Each v In Worksheets("Sheet2").Columns("B").SpecialCells(xlCellTypeConstants)
filepath = v.Value
debug.Print filePath
.... ' remainder of your code
.. then go to the Next line and write another Next line after it.

Excel VBA for searching String within an Outlook Attachment, flagging email if match is found

Basically I have a list of 5000 strings populated in an Excel spreadsheet. I want VBA to go through the attachments in an Outlook Inbox and if it finds a string match, I want the particular email to be flagged. Here's the code I have so far
Sub attachsearch()
On Error GoTo bigerror
Dim ns As Namespace
Dim inbox As MAPIFolder
Dim subfolder As MAPIFolder
Dim item As Object
Dim atmt As Attachment
Dim filename As String
Dim i As Integer
Dim varresponse As VbMsgBoxResult
Dim workbk As Workbook
Dim SearchString As String
Set ns = GetNamespace("MAPI")
Set inbox = ns.GetDefaultFolder(olFolderInbox)
Set subfolder = inbox.Folders("test")
Set workbk = Workbooks.Open("C:\Users\John.Doe\Desktop\10 25 2016 Pricing Team Macro.xlsm")
i = 0
If subfolder.Items.Count = 0 Then
MsgBox "There are no emails to look at. Please stop wasting my time.", vbInformation, "Folder is Empty"
Exit Sub
End If
For Each item In subfolder.Items
For Each atmt In item.Attachments
For rwindex = 1 To 5000
SearchString = Workbooks("10 25 2016 Pricing Team Macro").Sheets("NDC Sort").Cells(rwindex, 1).Value
Below is the problem code, index proberty is not used correctly here, but I'm unsure what to use. I know that Microsoft indexes the words within the attachment because when I manually type in the search string in Outlook, it pulls up the email even though the string is only present within the attachment. So ultimately, my question is, how do I leverage that attachment index in VBA?
If atmt.Index Like "*" & Workbooks("10 25 2016 Pricing Team Macro").Sheets("NDC Sort").Cells(rwindex, 1).Value & "*" Then
i = i + 1
With item
.FlagRequest = "Follow up"
.Save
End With
End If
Next rwindex
Next atmt
Next item
If i > 0 Then
MsgBox "I found " & i & " attached files with a specific name."
Else
MsgBox "I didn't find any files"
End If
Set atmt = Nothing
Set item = Nothing
Set ns = Nothing
workbk.Close savechanges:=False
Exit Sub
bigerror:
MsgBox "something went wrong"
End Sub
Any help would be greatly appreciated, thanks in advance!
Here's a solution if you only need to search the contents PDFs, MSWord, and Excel. There's a different procedure for each. A caveat is that you need to have a version of Adobe that you pay for. This won't work on plain Adobe Reader. I've tested it a few times and it works, but it seems kind of chunky in some parts so I'm open to suggestions.
Sub attachsearch()
Dim ns As Namespace
Dim inbox As MAPIFolder
Dim subfolder As MAPIFolder
Dim item As Object
Dim atmt As Attachment
Dim tempfilepath As String
Dim tempfilename As String
Dim i As Integer
Dim workbk As Workbook
Dim LastRow As Long
Dim TextToFind As String
Dim Loc As Range
Dim Sh As Worksheet
Dim WS_Count As Integer
Dim x As Integer
Dim WS_Name As String
Set ns = GetNamespace("MAPI")
Set inbox = ns.GetDefaultFolder(olFolderInbox)
Set subfolder = inbox.Folders("test")
Set workbk = Workbooks.Open("C:\Users\John.Doe\Desktop\10 25 2016 Pricing Team Macro.xlsx")
LastRow = Workbooks("10 25 2016 Pricing Team Macro").Worksheets("NDC Sort").Cells(Worksheets("NDC Sort").Rows.Count, "A").End(xlUp).Row
i = 0
If subfolder.Items.Count = 0 Then
MsgBox "There are no emails to look at. Please stop wasting my time.", vbInformation, "Folder is Empty"
Exit Sub
End If
For Each item In subfolder.Items
For Each atmt In item.Attachments
If item.FlagStatus = Empty Then
If Right(atmt.Filename, 4) Like "xl**" Or Right(atmt.Filename, 3) Like "xl*" Then
tempfilepath = "O:\aaaTEST\"
tempfilename = Format(item.ReceivedTime, "yyyymmdd_hhnnss_") & item.SenderName & "_" & atmt.Filename
atmt.SaveAsFile tempfilepath & tempfilename
Workbooks.Open (tempfilepath & tempfilename)
Workbooks(tempfilename).Activate
WS_Count = Workbooks(tempfilename).Worksheets.Count
'Clearing any selections that may limit the search unintentionally
For x = 1 To WS_Count
With ActiveWorkbook.Worksheets(x)
.Select
.Cells(1, 1).Select
Application.CutCopyMode = False
End With
Next x
For rwindex = 2 To LastRow
If item.FlagStatus = Empty Then
TextToFind = Workbooks("10 25 2016 Pricing Team Macro").Sheets("NDC Sort").Cells(rwindex, 1).Value
If TextToFind <> "" Then
Workbooks(tempfilename).Activate
For x = 1 To WS_Count
With ActiveWorkbook.Worksheets(x)
.Select
.UsedRange.Select
Set Loc = .Cells.Find(TextToFind)
If item.FlagStatus = Empty Then
If Not Loc Is Nothing Then
i = i + 1
With item
.FlagRequest = "Follow up"
.Save
End With
End If
End If
Set Loc = Nothing
End With
Next x
End If
End If
Next rwindex
Workbooks(tempfilename).Close Savechanges:=False
End If
'PDF Check
If Right(atmt.Filename, 3) = "pdf" Then
tempfilename = "O:\aaaTEST\" & _
Format(item.ReceivedTime, "yyyymmdd_hhnnss_") & item.SenderName & "_" & atmt.Filename
atmt.SaveAsFile tempfilename
PDFPath = tempfilename
Set App = CreateObject("AcroExch.App", "")
Set AVDoc = CreateObject("AcroExch.AVDoc")
If AVDoc.Open(PDFPath, "") = True Then
AVDoc.BringToFront
For rwindex = 2 To 3593
If item.FlagStatus = Empty Then
TextToFind = Workbooks("10 25 2016 Pricing Team Macro").Sheets("NDC Sort").Cells(rwindex, 1).Value
If AVDoc.FindText(TextToFind, False, True, False) = True Then
i = i + 1
With item
.FlagRequest = "Follow up"
.Save
End With
End If
AVDoc.Close True
App.Exit
End If
Next rwindex
End If
End If
'MSWord check
If Right(atmt.Filename, 4) Like "doc*" Or Right(atmt.Filename, 3) Like "doc" Then
tempfilepath = "O:\aaaTEST\"
tempfilename = Format(item.ReceivedTime, "yyyymmdd_hhnnss_") & item.SenderName & "_" & atmt.Filename
atmt.SaveAsFile tempfilepath & tempfilename
Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open Filename:=tempfilepath & tempfilename
wordapp.Visible = True
For rwindex = 2 To 5
If item.FlagStatus = Empty Then
TextToFind = Workbooks("10 25 2016 Pricing Team Macro").Sheets("NDC Sort").Cells(rwindex, 1).Value
If TextToFind <> "" Then
With wordapp.ActiveDocument.Content.Find
.ClearFormatting
.Execute FindText:=TextToFind
If .Found = True Then
i = i + 1
With item
.FlagRequest = "Follow up"
.Save
End With
End If
End With
End If
End If
Next rwindex
wordapp.ActiveDocument.Close Savechanges:=wdDoNotSaveChanges
wordapp.Quit Savechanges:=wdDoNotSaveChanges
End If
End If
Next atmt
Next item
Workbooks("10 25 2016 Pricing Team Macro").Close Savechanges:=False
If i > 0 Then
MsgBox "I found " & i & " attached files with a specific name."
Else
MsgBox "I didn't find any files"
End If
Set atmt = Nothing
Set item = Nothing
Set ns = Nothing
Exit Sub
End Sub

Run-time error '1004' Method 'Save' of object '_Workbook' failed

I got this error while running an VBA application. I think this error is related to the following line in my code
ActiveWorkbook.Save
This is the whole code.
LDate = Date
LDate = Mid(LDate, 4, 2)
If LDate > 8 Then
Sheets("a").Cells(13, "H").Value = Sheets("a").Cells(13, "H").Value + 1000
Else
Sheets("a").Cells(13, "H").Value = Sheets("a").Cells(13, "H").Value + 1
End If
ActiveWorkbook.Save
Can someone explain the cause of this error and how I can tackle it.
Please read below comments.
This is the subroutine that is getting executed when the first button is clicked.
Sub import()
Dim Filt As String
Dim FilterIndex As Integer
Dim Title As String
Dim FileName As Variant
Dim finalrow As Integer
Dim alldata As String
Dim temp As String
Dim oFSO As New FileSystemObject
Dim oFS As TextStream
'Filt = "Cst Files (*.txt),*.txt"
'Title = "Select a cst File to Import"
'FileName = Application.GetOpenFilename(FileFilter:=Filt, Title:=Title)
'If FileName = False Then
'MsgBox "No File Was Selected"
'Exit Sub
'End If
'Call TestReference
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
If diaFolder.SelectedItems.Count <> 0 Then
folderpath = diaFolder.SelectedItems(1)
folderpath = folderpath & "\"
'MsgBox diaFolder.SelectedItems(1)
Set diaFolder = Nothing
'RefreshSheet
On Error Resume Next
temp = folderpath & "*.txt"
sFile = Dir(temp)
Do Until sFile = ""
inputRow = Sheets("RawData").Range("A" & Rows.Count).End(xlUp).Row + 1
FileName = folderpath & sFile
Set oFS = oFSO.OpenTextFile(FileName)
Dim content As String
content = oFS.ReadAll
content = Mid(content, 4, Len(content) - 3)
With Sheets("RawData").Range("A" & inputRow)
.NumberFormat = "#"
.Value = content
End With
oFS.Close
Set oFS = Nothing
alldata = ""
finalrow = Sheets("RawData").Cells(Rows.Count, 1).End(xlUp).Row
Sheets("RawData").Activate
For i = inputRow To finalrow
alldata = alldata & Cells(i, "A").Value & " "
Cells(i, "A").Value = ""
Next i
Cells(inputRow, "B").Value = alldata
temp = StrReverse(FileName)
temp = Left(temp, InStr(1, temp, "\") - 1)
temp = StrReverse(temp)
temp = Left(temp, InStr(1, temp, ".") - 1)
Cells(inputRow, "A").Value = temp
Sheets("RawData").Cells(inputRow, "A").NumberFormat = "#"
sFile = Dir()
Loop
Else
MsgBox ("No Folder Selected")
End If
End Sub
How to make this code stop accessing the worksheet after executing this macro?
Although I think you should seriously consider refactoring your code, you should begin by referencing the correct workbook called by the .Save() Method.
Workbooks("Insert_Workbook_Name_Here.xlsm").Save
Make sure that the workbook name and extension (.xlsm, .xls, .xlsx) match the file you are actually trying to save.
This error happened in a macro that I wrote as well. I have this code to close a dialogue box.
Private Sub CancelButton_Click()
Unload Me
ThisWorkbook.Save
End
End Sub
I received the same error because the workbook that was being loaded was from a "last saved" copy due to an update reboot that happened while the original was open. Not sure how to avoid that in the future but thought it might be helpful to someone.