Im trying to download attachment from certain Lotus Notes e-mails. The code below works but it goes in infinite loop (code execution never ends after the procedure) after saving all required files. Something is wrong with Do until command I guess. Would appreaciate some help in fixing this issue.
Sub Test2Dobre()
Dim sess As Object
Dim db As Object
Dim view As Object
Dim doc As Object
Dim docNext As Object
Dim mailServer As String
Dim mailFile As String
Dim fld1 As String
Dim strSQL As String
Const stPath As String = "C:\Users\kuckam\Desktop\test notes\"
Const EMBED_ATTACHMENT As Long = 1454
Const RICHTEXT As Long = 1
Dim vaItem As Variant
Dim vaAttachment As Variant
Set sess = CreateObject("Notes.NotesSession")
'Call sess.Initialize(Password)
Dim objADOConnection As Object
Set objADOConnection = CreateObject("ADODB.Connection")
'to get your mail db:
mailServer = sess.GetEnvironmentString("MailServer", True)
mailFile = sess.GetEnvironmentString("MailFile", True)
Set db = sess.GetDatabase(mailServer, mailFile)
'Get Inbox folder:
Set view = db.GetView("($Inbox)")
'Loop through all documents in Inbox:
Set doc = view.GetFirstDocument
Do Until doc Is Nothing
Set docNext = view.GetNextDocument(doc)
If doc.HasEmbedded And doc.GetItemValue("From")(0) = "<Protokoly.warszawa#linde-mh.pl>" Then
MsgBox doc.GetItemValue("subject")(0)
'MsgBox doc.GetItemValue("From")(0)
'Check if the document has an attachment or not.
Set vaItem = doc.GetFirstItem("Body")
If vaItem.Type = RICHTEXT Then
For Each vaAttachment In vaItem.EmbeddedObjects
If vaAttachment.Type = EMBED_ATTACHMENT Then
'Save the attached file into the new folder and remove it from the e-mail.
With vaAttachment
.ExtractFile stPath & vaAttachment.Name
' .Remove
End With
End If
Next vaAttachment
End If
End If
Set doc = docNext
Loop
End Sub
EDIT:
Posting working code:
Function ADOExecSQL(strSQL As String)
ADOExecSQL = 1
On Error GoTo ERROR_FUNCTION
If ADODbConnect() = 0 Then GoTo ERROR_FUNCTION
cnConn.Execute strSQL
EXIT_FUNCTION:
Exit Function
ERROR_FUNCTION:
ADOExecSQL = 0
GoTo EXIT_FUNCTION
End Function
Sub Test2Dobre()
Dim sess As Object
Dim db As Object
Dim view As Object
Dim doc As Object
Dim docNext As Object
Dim mailServer As String
Dim mailFile As String
Dim fld1 As String
Dim strSQL As String
Const stPath As String = "C:\Users\kuckam\Desktop\test notes\"
Const EMBED_ATTACHMENT As Long = 1454
Const RICHTEXT As Long = 1
Dim vaItem As Variant
Dim vaAttachment As Variant
Set sess = CreateObject("Notes.NotesSession")
'Call sess.Initialize(Password)
Dim objADOConnection As Object
Set objADOConnection = CreateObject("ADODB.Connection")
'to get your mail db:
mailServer = sess.GetEnvironmentString("MailServer", True)
mailFile = sess.GetEnvironmentString("MailFile", True)
Set db = sess.GetDatabase(mailServer, mailFile)
'Get Inbox folder:
Set view = db.GetView("($Inbox)")
view.AutoUpdate = False
'Loop through all documents in Inbox:
Set doc = view.GetFirstDocument
Do Until doc Is Nothing
Set docNext = view.GetNextDocument(doc)
'If doc.HasEmbedded And doc.GetItemValue("From")(0) = "<Protokoly.warszawa#linde-mh.pl>" Then
'If doc.GetItemValue("From")(0) = "<Protokoly.warszawa#linde-mh.pl>" Then
'MsgBox doc.GetItemValue("subject")(0)
'MsgBox doc.GetItemValue("From")(0)
'Check if the document has an attachment or not.
Set vaItem = doc.GetFirstItem("Body")
On Error GoTo Line1
If vaItem.Type = RICHTEXT And doc.GetItemValue("From")(0) = "<Protokoly.warszawa#linde-mh.pl>" Then
For Each vaAttachment In vaItem.EmbeddedObjects
If vaAttachment.Type = EMBED_ATTACHMENT Then
'Save the attached file into the new folder and remove it from the e-mail.
With vaAttachment
.ExtractFile stPath & vaAttachment.Name
' .Remove
End With
End If
'Save the e-mail in order to reflect the deleting of the attached file.
'(A more sophisticated approach may be considered if several e-mails have
'several attachments in order to avoid a repeately saving of one e-mail.)
doc.Save True, False
Next vaAttachment
End If
'End If
'Call Attachment.ExtractFile("C:\Users\kuckam\Desktop\test notes")
'Call doc.PutInFolder("C:\Users\kuckam\Desktop\test notes")
Set doc = docNext
Loop
'Release objects from memory.
Set docNext = Nothing
Set doc = Nothing
Set view = Nothing
Set sess = Nothing
Set db = Nothing
Set objADOConnection = Nothing
Set vaItem = Nothing
Line1:
End Sub
Related
This was working fine, only sometimes I get this error, but it is happening more and more. Like it will work one a group of invoices, I will try it agian and it works on like half of them the next time. It is breaking at the .Paste Just cant firgure out what it is. I am converting PDF to Excel. This method has given me the best results so for and all my other code that works from the output is already writtten
Sub PDF_To_Excel()
Dim automate_sh As Worksheet
Set automate_sh = ThisWorkbook.Sheets("Automate")
Dim pdf_path As String
Dim excel_path As String
pdf_path = automate_sh.Range("E11").Value
excel_path = automate_sh.Range("E12").Value
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Set fo = fso.GetFolder(pdf_path)
Dim wa As Object
Dim doc As Object
Dim wr As Object
Set wa = CreateObject("word.application")
wa.Visible = True
Dim nwb As Workbook
Dim nsh As Worksheet
For Each f In fo.Files
Set doc = wa.documents.Open(f.Path, False, Format:="PDF Files")
Set wr = doc.Paragraphs(1).Range
wr.WholeStory
Set nwb = Workbooks.Add
Set nsh = nwb.Sheets(1)
wr.Copy
nsh.Paste
nwb.SaveAs (excel_path & "\" & Replace(f.Name, ".pdf", ".xlsx"))
doc.Close False
nwb.Close False
Next
wa.Quit
MsgBox "Done"
End Sub
Is there a way to get the attachment to appear with the correct icon when you add it through the macro inside body of email?. My issue is that when attaching a .pdf or .xlsx through my lotus notes macro it appears as a generic grey icon rather than the .pdf or .xlsx icon. I tried only saving a draft of the email and it shows the .pdf or .xlsx icon but when I switched my macro to display the email it shows a generic grey one.
Private Maildb As Object ' The Mail Database
Private Username As String ' The current users notes name
Private MailDbName As String ' The Current Users Notes mail database name
Private MailDoc As Object 'the mail document itself
Private AttachME As Object ' The attachement richtextfile object
Private session As Object ' The Notes Seesion
Private EmbedObj As Object ' The Embedded Object (attachment)
Private ws As Object 'Lotus Workspace
Private objProfile As Object
Private rtiSig As Object, rtitem As Object, rtiNew As Object
Private uiMemo As Object
Public strToArray() As String, strCCArray() As String, strBccArray() As String
'
Public Function f_SendNotesEmail(strAtask As String, strTo As String, strCC As String, strBcc As String, _
strObject As String, strBody As String, blnSaveIt As Boolean) As Boolean
Dim strSignText As String, strMemoUNID As String
Dim intSignOption As Integer
Set session = CreateObject("Notes.NotesSession")
Set ws = CreateObject("Notes.NotesUIWorkspace")
Username = session.Username
MailDbName = Left$(Username, 1) & Right$(Username, (Len(Username) - InStr(1, Username, " "))) & ".nsf"
On Error GoTo err_send
Set Maildb = session.GETDATABASE("", MailDbName)
If Maildb.IsOpen = False Then Maildb.OPENMAIL
Set MailDoc = Maildb.CREATEDOCUMENT
MailDoc.Form = "Memo"
MailDoc.SendTo = strTo
MailDoc.CopyTo = strCC
'MailDoc.BlindCopyTo = strBcc
MailDoc.subject = strObject
MailDoc.SAVEMESSAGEONSEND = blnSaveIt
Set objProfile = Maildb.GetProfileDocument("CalendarProfile")
intSignOption = objProfile.GetItemValue("SignatureOption")(0)
strSignText = objProfile.GetItemValue("Signature")(0)
'Signature or not
If intSignOption = 0 Then
MailDoc.body = strBody
Else
'Insert a Signature
Select Case intSignOption
Case 1: 'Plain text Signature
Set rtitem = MailDoc.CreateRichTextItem("Body")
Call rtitem.AppendText(strBody)
Call rtitem.AppendText(Chr(10)): Call rtitem.AppendText(Chr(10))
Call rtitem.AppendText(strSignText)
Case 2, 3: 'Document or Rich text
'Open memo in ui
Set uiMemo = ws.EditDocument(True, MailDoc)
Call uiMemo.GotoField("Body")
'Check if the signature is automatically inserted
If objProfile.GetItemValue("EnableSignature")(0) <> 1 Then
If intSignOption = 2 Then
Call uiMemo.Import(f_strSignatureType(strSignText), strSignText)
Else
Call uiMemo.ImportItem(objProfile, "Signature_Rich")
End If
End If
Call uiMemo.GotoField("Body")
'Save the mail doc
strMemoUNID = uiMemo.Document.UniversalID
uiMemo.Document.MailOptions = "0"
Call uiMemo.Save
uiMemo.Document.SaveOptions = "0"
Call uiMemo.Close
Set uiMemo = Nothing
Set MailDoc = Nothing
'Get the text and the signature
Set MailDoc = Maildb.GetDocumentByUNID(strMemoUNID)
Set rtiSig = MailDoc.GetFirstItem("Body")
Set rtiNew = MailDoc.CreateRichTextItem("rtiTemp")
Call rtiNew.AppendText(strBody)
Call rtiNew.AppendText(Chr(10)): Call rtiNew.AppendText(Chr(10))
strFile = Dir(strPath & "*.xlsx")
Do While Len(strFile) > 0
'.AppendText ("hiui")
'Set AttachME = MailDoc.CreateRichTextItem("ATTACHMENT" & strFile) 'attaching as attachments not inside body
Call rtiNew.embedobject(1454, "", strPath & strFile, "ATTACHMENT")
'.AddNewLine (1)
strFile = Dir
Loop
Call rtiNew.AppendRTItem(rtiSig)
'Remove actual body to replace it with the new one
Call MailDoc.RemoveItem("Body")
Set rtitem = MailDoc.CreateRichTextItem("Body")
Call rtitem.AppendRTItem(rtiNew)
End Select
End If
MailDoc.Save False, False
Set uiMemo = ws.EditDocument(True, MailDoc)
f_SendNotesEmail = True
label_end:
Set Maildb = Nothing
Set MailDoc = Nothing
Set AttachME = Nothing
Set session = Nothing
Set EmbedObj = Nothing
Set rtitem = Nothing
Set uiMemo = Nothing
Set rtiSig = Nothing
Set rtiNew = Nothing
Set ws = Nothing
Exit Function
err_send:
f_SendNotesEmail = False
GoTo label_end
End Function
Showing the correct icon only works when done in the frontend. Whenever you use LotusScript to attach something in the backend, the symbol will always be the default one. There are workarounds with XML- Export / Import, but usually they are not feasible.
I'm trying to write a macro that will generate a Microsoft Word 'report' from an Excel file. I want for the macro to navigate to bookmarks in a Word template for the report, and insert at each certain content or a chart from the native Excel file. The macro works when running in piecemeal, but altogether fails to execute, with Excel repeating over and over that "[It] is waiting for another application to complete an OLE action."
To clarify also, the macro first clears a certain 'data dump' region in the workbook (its native file) and repopulates it with new data from a specified file. This file (its location path) and the various 'target row' and 'identifier' variables you see in the code are inputted by the user to a sort of interface (just a worksheet in the native workbook), where each is labeled manually as a (named) range to be easily fed into to be used by the code. The macro then creates the report by going through the different sheets of the workbook, copying certain content, and turning to Word to paste the copied content at template locations indicated by bookmarks.
I'm completely perplexed by the 'OLE error'. Any ideas about this/the code otherwise? Please share. Thanks for your help!
Sub GenerateReport()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Dim myWorkbook As Excel.Workbook
Set myWorkbook = ThisWorkbook
Dim myWorksheet As Excel.Worksheet
Set myWorksheet = myWorkbook.Sheets("Sheet1")
Dim myWorksheet2 As Excel.Worksheet
Set myWorksheet2 = myWorkbook.Sheets("Sheet2")
Dim myWorksheet3 As Excel.Worksheet
Set myWorksheet3 = myWorkbook.Sheets("Sheet3")
Dim FileName As String
FileName = myWorksheet.Range("FileName")
Dim FilePath As String
FilePath = myWorksheet.Range("FilePath")
Dim TargetSheetName As String
TargetSheetName = myWorksheet.Range("TargetSheetName")
Dim PasteSheetName As String
PasteSheetName = myWorksheet.Range("PasteSheetName")
Dim Identifier As String
Identifier = myWorksheet.Range("Identifier")
Dim Identifier2 As String
Identifier2 = myWorksheet.Range("Identifier2")
Dim TargetRow As String
TargetRow = myWorksheet.Range("TargetRow")
Dim TargetRow2 As String
TargetRow2 = myWorksheet.Range("TargetRow2")
Dim PasteIdentifier As String
PasteIdentifier = myWorksheet.Range("PasteIdentifier")
Dim PasteIdentifier2 As String
PasteIdentifier2 = myWorksheet.Range("PasteIdentifier2")
Dim PasteTargetRow As String
PasteTargetRow = myWorksheet.Range("PasteTargetRow")
Dim PasteTargetRow2 As String
PasteTargetRow2 = myWorksheet.Range("PasteTargetRow2")
Dim Text As String
Text = myWorksheet.Range("Text")
Dim Text2 As String
Text2 = myWorksheet.Range("Text2")
Dim Text3 As String
Text3 = myWorksheet.Range("Text3")
Dim ReportTemplateFilePath As String
ReportTemplateFilePath = myWorksheet.Range("ReportTemplateFilePath")
Dim ReportTemplateFileName As String
ReportTemplateFileName = myWorksheet.Range("ReportTemplateFileName")
Dim SaveToLocation As String
SaveToLocation = myWorksheet.Range("SaveToLocation")
Dim SourceTargetSheet As Excel.Worksheet
Set SourceTargetSheet = myWorkbook.Sheets(PasteSheetName)
Dim TargetWorkbook As Excel.Workbook
Set TargetWorkbook = Workbooks.Open(FilePath)
Dim TargetSheet As Excel.Worksheet
Set TargetSheet = TargetWorkbook.Sheets(TargetSheetName)
'Clear old info
Dim UpperLeftHandCornerOfClear As String
UpperLeftHandCornerOfClear = "A" & PasteTargetRow
Dim LowerRightHandCornerOfClear As String
LowerRightHandCornerOfClear = "XFD" & PasteTargetRow2
SourceTargetSheet.Range(UpperLeftHandCornerOfClear, LowerRightHandCornerOfClear).ClearContents
'Copy new info for pasting
Dim StartingColumnAsRange As Range
Set StartingColumnAsRange = TargetSheet.Cells.Find(Identifier, LookIn:=xlValues, LookAt:=xlPart)
If Not StartingColumnAsRange Is Nothing Then
Dim StartingColumn As String
StartingColumn = Split(StartingColumnAsRange.Address, "$")(1)
End If
Dim EndingColumnAsRange As Range
Set EndingColumnAsRange = TargetSheet.Cells.Find(Identifier2, LookIn:=xlValues, LookAt:=xlPart)
If Not EndingColumnAsRange Is Nothing Then
Dim EndingColumn As String
EndingColumn = Split(EndingColumnAsRange.Address, "$")(1)
End If
Dim UpperLeftHandCornerOfCopy As String
UpperLeftHandCornerOfCopy = StartingColumn & TargetRow
Dim LowerRightHandCornerOfCopy As String
LowerRightHandCornerOfCopy = EndingColumn & TargetRow2
TargetSheet.Range(UpperLeftHandCornerOfCopy, LowerRightHandCornerOfCopy).Copy
Dim PastePasteTarget As String
PastePasteTarget = "A" & PasteTargetRow
SourceTargetSheet.Range(PastePasteTarget).PasteSpecial Paste:=xlPasteValues
'Create a Microsoft Word object (instance of Word to control)
Dim WordApplication As Word.Application
Set WordApplication = CreateObject("Word.Application")
'Error handle if Microsoft Word is open
On Error Resume Next
Set WordApplication = GetObject(class:="Word.Application")
Err.Clear
If WordApplication Is Nothing Then
Set WordApplication = CreateObject(class:="Word.Application")
End If
On Error GoTo 0
'Error handle if report template is specifically already open
On Error Resume Next
Application.DisplayAlerts = False
Documents(ReportTemplateFileName).Close SaveChanges:=wdDoNotSaveChanges
On Error GoTo 0
Application.DisplayAlerts = True
Dim WordDocument As Word.Document
Set WordDocument = WordApplication.Documents.Open(ReportTemplateFilePath)
'Content from 'myWorksheet'
With WordDocument
.Bookmarks("Bookmark1").Range.Text = myWorksheet.Range("Text1")
.Bookmarks("Bookmark2").Range.Text = myWorksheet.Range("Text2")
.Bookmarks("Bookmark3").Range.Text = myWorksheet.Range("Text3")
.Bookmarks("Bookmark4").Range.Text = myWorksheet.Range("Text4")
End With
'Content from 'myWorksheet2'
With WordDocument
.Bookmarks("Bookmark5").Range.Text = myWorksheet2.Range("Text5")
.Bookmarks("Bookmark6").Range.Text = myWorksheet2.Range("Text6")
.Bookmarks("Bookmark7").Range.Text = myWorksheet2.Range("Text7")
.Bookmarks("Bookmark8").Range.Text = myWorksheet2.Range("Text8")
.Bookmarks("Bookmark9").Range.Text = myWorksheet2.Range("Text9")
.Bookmarks("Bookmark10").Range.Text = myWorksheet3.Range("Text10")
End With
'Chart (alone on worksheet)
WordApplication.Selection.Goto What:=wdGoToBookmark, Name:="Chart1"
ThisWorkbook.Sheets("Chart 1 Worksheet Name").ChartObjects(1).Copy
WordApplication.Selection.Paste
WordApplication.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
'Two charts grouped together
WordApplication.Selection.Goto What:=wdGoToBookmark, Name:="Chart2"
ThisWorkbook.Sheets("Chart 2 Worksheet Name").ChartObjects(1).Copy
WordApplication.Selection.Paste
WordApplication.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
With WordDocument
.SaveAs FileName:=SaveToLocation & " " & Text3, _
FileFormat:=wdFormatDocumentDefault
.Close
End With
WordApplication.Quit
Set WordApplication = Nothing
Set WordDocument = Nothing
Application.ScreenUpdating = True
'Application.DisplayAlerts = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
myWorksheet.Activate
MsgBox "Report successfully generated.", vbInformation, "Completed!"
End Sub
Try modifying your Word application creation script - this is all you need:
On Error Resume Next
Set WordApplication = GetObject(class:="Word.Application")
On Error GoTo 0
If WordApplication Is Nothing Then
Set WordApplication = CreateObject(class:="Word.Application")
End If
It may be that Word is waiting for some input from you but you're not seeing it because you didn't make the instance visible, so try also adding:
WordApplication.Visible = True
I'm trying to write code that will read a value from Excel, look it up in an internal web based system and store the results back in the Excel. It reads the Excel with no problem, opens Internet Explorer with no problem, but when I then try to reference what's been opened, I get the above error. The line "ie.Navigate url" works, but the next line "Set DOC = ie.Document" generates the error. Any ideas on what's causing this? Here's my code:
Public Sub getClient()
Dim xOpen As Boolean
xOpen = False
Dim row As Long
Dim xL As Excel.Application
Set xL = New Excel.Application
xL.Visible = False
Dim wb As Excel.Workbook
Dim sh As Excel.Worksheet
'Change the name as needed, out put in some facility to input it or
'process multiples...
Dim filename As String
filename = "auditLookup.xlsx"
Set wb = xL.Workbooks.Open(getPath("Audit") + filename)
xOpen = True
Set sh = wb.Sheets(1)
Dim ie As Variant
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
Dim DOC As HTMLDocument
Dim idx As Integer
Dim data As String
Dim links As Variant
Dim lnk As Variant
Dim iRow As Long
iRow = 2 'Assume headers
Dim clientName As String
Dim clientID As String
Dim nameFound As Boolean
Dim idFound As Boolean
Dim url As String
While sh.Cells(iRow, 1) <> ""
'Just in case these IDs are ever prefixed with zeroes, I'm inserting
'some random character in front, but removing it of course when
'processing.
url = "https://.../" + mid(sh.Cells(iRow, 1), 2)
ie.navigate url
Set DOC = ie.Document
'Search td until we find "Name:" then the next td will be the name.
'Then search for "P1 ID (ACES):" and the next td with be that.
Set links = DOC.getElementsByTagName("td")
clientName = ""
clientID = ""
nameFound = False
idFound = False
For Each lnk In links
data = lnk.innerText
If nameFound Then
clientName = data
ElseIf idFound Then
clientID = data
End If
If nameFound And idFound Then
Exit For
End If
If data = "Name:" Then
nameFound = True
ElseIf data = "P1 ID (ACES):" Then
idFound = True
End If
Next
sh.Cells(iRow, 2) = clientName
sh.Cells(iRow, 2) = clientID
iRow = iRow + 1
Wend
Set ie = Nothing
If xOpen Then
wb.Save
Set wb = Nothing
xL.Quit
Set xL = Nothing
Set sh = Nothing
xOpen = False
End If
Exit Sub
Changing to:
Dim ie As InternetExplorer
Set ie = New InternetExplorerMedium
...
Solved the problem. Plus I did need to add back the Do loop mentioned in the comments:
Do
DoEvents
Loop Until ie.ReadyState = READYSTATE_COMPLETE
I have a file name of a pdf that I want to search for in a folder on a shared network drive \\Share\Projects. The pdf will be in one of the subfolders under projects. I then want to return the entire file path of the pdf into a cell (eg \\Share\Projects\Subfolder\Another subfolder\thisone.pdf).
I have started the code but can't figure out how to search a file system:
Sub InsertPath()
Dim PONumber As String
PONumber = InputBox("PO Number:", "PO Number")
'search for order
Dim myFolder As Folder
Dim myFile As File
'This bit doesn't work
Set myFolder = "\\Share\Projects"
For Each myFile In myFolder.Files
If myFile.Name = "PO" & PONumber & ".pdf" Then
'I have absolutely no idea how to do this bit
End If
Next
End Sub
Am I on the right track or is my code completely wrong?
get list of subdirs in vba
slighly modified the above post.
Public Arr() As String
Public Counter As Long
Sub LoopThroughFilePaths()
Dim myArr
Dim i As Long
Dim j As Long
Dim MyFile As String
Const strPath As String = "C:\Personal\" ' change it as per your needs
myArr = GetSubFolders(strPath)
Application.ScreenUpdating = False
Range("A1:B1") = Array("text file", "path")
For j = LBound(Arr) To UBound(Arr)
MyFile = Dir(myArr(j) & "\*.pdf")
Do While Len(MyFile) <> 0
i = i + 1
Cells(i, 1) = MyFile
Cells(i, 2) = myArr(j)
MyFile = Dir
Loop
Next j
Application.ScreenUpdating = True
End Sub
Function GetSubFolders(RootPath As String)
Dim fso As Object
Dim fld As Object
Dim sf As Object
Dim myArr
Set fso = CreateObject("Scripting.FileSystemObject")
Set fld = fso.GetFolder(RootPath)
For Each sf In fld.SUBFOLDERS
Counter = Counter + 1
ReDim Preserve Arr(Counter)
Arr(Counter) = sf.Path
myArr = GetSubFolders(sf.Path)
Next
GetSubFolders = Arr
Set sf = Nothing
Set fld = Nothing
Set fso = Nothing
End Function
Well, your folder declaration isn't set against a filesystemobject so it can't find the folder. And because it's a network location, you may need to map a network drive first so that it's a secure link.
So here's an updated version of your code.
EDIT - to OP's conditions.
Dim PONumber As String
Sub InsertPath()
PONumber = InputBox("PO Number:", "PO Number")
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim Servershare As String
ServerShare = "S:\"
Dim Directory As Object
Set Directory = fso.GetFolder(ServerShare)
Subfolderstructure Directory
End Sub
Function Subfolderstructure(Directory As Object)
For Each oFldr in Directory.SubFolders
For Each FileName In oFldr.Files
If FileName.Name = "PO" & PONumber & ".pdf" Then
sheets("Sheet1").range("A1").value = ServerShare & "\PO" & PONumber & ".pdf"
Exit For
End If
Next
Dim sbfldrs : Set sbfldrs = ofldr.SubFolders
If isarray(sbfldrs) then
Subfolderstructure ofldr
End if
Next
'Cleanup
Set FileName = Nothing
Set Directory = Nothing
Set fso = Nothing
End Function
I have not tested this code. Try it out and let me know how it works.