I am trying to open a file with a file name which changes every week. This means that the date part on the file name is varying. Also, this file is the ONLY file inside the folder. But its file name is changing. I am using the code below but it was throwing the error, 'Run time 52: Bad file name & number'. I need your help.
Dim ThePath As String
Dim TheFile As String
ThePath = "https://ts.company.com/sites/folder1/folder2/folder3/folder4/"
TheFile = Dir(ThePath & "MANILA_ShiftRecord_*" & ".xlsx")
Workbooks.Open (ThePath & TheFile)
Thanks!
If it's only one file you can use this approach:
Dim sharepointFolder As String
Dim colDisks As Variant
Dim objWMIService As Object
Dim objDisk As Variant
Dim driveLetter As String
'Create FSO and network object
Set objNet = CreateObject("WScript.Network")
Set fs = CreateObject("Scripting.FileSystemObject")
'Get all used Drive-Letters
Set objWMIService = GetObject("winmgmts:\\" & "." & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk")
'Loop through used Drive-Letters
For Each objDisk In colDisks
For i = 65 To 90
'If letter is in use exit loop and remember letter.
If i = Asc(objDisk.DeviceID) Then
j = i
Exit For
'letters which are not checked yet are possible only
ElseIf i > j Then
driveLetter = Chr(i) & ":"
Exit For
End If
Next i
'If a Drive-Letter is found exit the loop
If driveLetter <> "" Then
Exit For
End If
Next
'define path to SharePoint
sharepointFolder = "https://spFolder/Sector Reports/"
'Map the sharePoint folder to the free Drive-Letter
objNet.MapNetworkDrive driveLetter, sharepointFolder
'set the folder to the mapped SharePoint-Path
Set folder = fs.GetFolder(driveLetter)
Afterwards you can handle the folder with filesystemobject functions.
Related
I'm completely new to VB and I'm trying to extract the attachment which is saved available inside the .msg file using the below code.
Could someone help me if this is the right approach to do this ?
I'm facing below compiler errors. Could someone help me how to resolve this issue ?
Outlook.Attachment is not defined.
End Sub' must be preceded by a matching 'Sub'
Reference to a non-shared member requires an object reference.
Statement cannot appear within a method body. End of method assumed
Method arguments must be enclosed in parentheses.
Type 'Outlook.MailItem' is not defined.
Sub SaveOlAttachments()
Dim msg As Outlook.MailItem
Dim att As Outlook.Attachment
Dim strFilePath As String
Dim strAttPath As String
Dim strFile As String
strFilePath = "C:\Users\...\Desktop\Test\"
strAttPath = "C:\Users\...\extracted attachment\"
strFile = Dir(strFilePath & "<Doc Name>.msg")
Do While Len(strFile) > 0
msg = Application.CreateItemFromTemplate(strFilePath & strFile)
If msg.Attachments.Count > 0 Then
For Each att In msg.Attachments
att.SaveAsFile strAttPath & att.FileName
Next
End If
strFile = Dir
Loop
End Sub
First of all, check out the file path where you try to find the template:
msg = Application.CreateItemFromTemplate(strFilePath & strFile)
The strFilePath string may include the file name already:
strFile = Dir(strFilePath & "<Doc Name>.msg")
Second, make sure attachments are saved using unique file names:
att.SaveAsFile strAttPath & att.FileName
The FileName string can be the same in different emails. I'd recommend adding IDs or the current time and etc. to the file name to uniquely name attached files on the disk.
Here is the code we use to grab a daily report attachment. I left a few commented statements in case you might need them (we didn't).
Sub Extract_Outlook_Email_Attachments()
On Error GoTo ErrHandler
Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim folder As MAPIFolder
Dim OutlookMail As Variant
Dim i As Integer
Dim olNS As Outlook.Namespace
Dim objOwner As Outlook.Recipient
Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
Dim saveFolder As String
saveFolder = strAttPath ' SAVE THE ATTACHMENT TO
'this bit is added to get a shared email
Set objOwner = OutlookNamespace.CreateRecipient("SHARED FOLDER NAME")
objOwner.Resolve
If objOwner.Resolved Then
Debug.Print "Outlook GB Fulfillment is good."
Set folder = OutlookNamespace.GetSharedDefaultFolder(objOwner, olFolderInbox) 'can use olFolderInbox or olFolderSentMail
End If
'Write mail to spreadsheet - create named range, from and to dates on the spreadsheet
i = 1
For Each OutlookMail In folder.Items
' Debug.Print "SenderEmailAddress: " & OutlookMail.SenderEmailAddress
'If OutlookMail.SenderEmailAddress = "no-reply#OurCompany.com" Then
If OutlookMail.subject = "Daily Report" Then
' If OutlookMail.SenderName = "no-reply#OurCompany.com" And OutlookMail.Subject = "Daily New Subscriber Plan Election Fulfillment" And OutlookMail.Attachments(1) = "NewSubscriberPlanElectionFulfillment_Subscription.xls" Then
Debug.Print "Received: " & OutlookMail.ReceivedTime
Debug.Print "Attach: " & OutlookMail.Attachments(1)
dateformat = Format(OutlookMail.ReceivedTime, "m-d-yy")
Debug.Print dateformat
FName = dateformat & " " & OutlookMail.Attachments(1).fileName
Debug.Print "FName: " & FName
Dim strFileExists As String
strFileExists = Dir(saveFolder & FName)
If strFileExists = "" Then
' MsgBox "The selected file doesn't exist"
Else
' MsgBox "The selected file exists"
Exit Sub
End If
OutlookMail.Attachments(1).SaveAsFile saveFolder & FName
Set outAttachment = Nothing
End If
Next OutlookMail
Set folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing
ErrHandler:
Debug.Print Err.Description
End Sub
Instead of using CreateItemFromTemplate, you can use Namespace.OpenSharedItem to open an MSG file.
You also need to add Outlook to your VB.Net project references.
I have emails with pdf attachments I would like to save automatically as they come into my inbox. I have my code mostly written, I have tested that all the variables have the correct value, and they output the correct data; however, I'm not sure how to code the actual saving of the file.
The file will get renamed to the customer's address, which is extracted with my code below:
Sub EagleViewSaveAttachment()
'Define Variables
Dim sFileName As String
Dim varAddress As Variant
Dim City As Variant
Dim fdObj As Object
Dim NextFriday As Date
Dim JobArea As String
Dim JobCity As Variant
Dim myPath As String
Dim objAtt As Outlook.Attachment
Dim myFinalPath As String
'Set Variables
NextFriday = Date + 8 - Weekday(Date, vbFriday)
myPath = "C:\Users\admin\OneDrive\Documents\EagleView\"
Set myfolder = Outlook.ActiveExplorer.CurrentFolder
Set fdObj = CreateObject("Scripting.FileSystemObject")
'Loop through emails in folder
For i = 1 To myfolder.Items.Count
Set myitem = myfolder.Items(i)
msgtext = myitem.Body
'Search for Specific Text
delimitedMessage = Replace(msgtext, "Address: ", "###")
delimitedMessage = Replace(delimitedMessage, ",", "###")
varAddress = Split(delimitedMessage, "###")
'Assign the job address from email to variable
sFileName = varAddress(10)
JobCity = LTrim(varAddress(11))
'Define office area based on job city
If JobCity = "Panama City" Or JobCity = "Mexico Beach" Or JobCity = "Panama City Beach" Or JobCity = "Lynn Haven" Or JobCity = "Port Saint Joe" Then
JobArea = "Panama"
ElseIf JobCity = "Daytona Beach" Or JobCity = "Port Orange" Or JobCity = "Deltona" Or JobCity = "Ormond Beach" Or JobCity = "Deland" Then
JobArea = "Daytona"
ElseIf JobCity = "Orlando" Then
JobArea = "Orlando"
ElseIf JobCity = "Jacksonville" Then
JobAre = "Jacksonville"
Else
JobArea = LTrim(varAddress(11))
End If
'Define Final Path
myFinalPath = myPath + Format$(NextFriday, "yyyy-mm-dd") + "\" + JobArea + "\"
'Check if the path exists, if not create it
If fdObj.FolderExists(myFinalPath) Then
MsgBox "Found it."
Else
fdObj.CreateFolder (myFinalPath)
MsgBox "It has been created."
End If
Next
End Sub
As of right now, what I am unable to do is get it to check if the directory C:\Users\admin\OneDrive\Documents\EagleView\yyyy-mm-dd\JobArea already exists and to create it if it doesn't already exist.
I'm fairly certain the problem lies in my usage of fdObj.FolderExists(myFinalPath) as it seems that doesn't accept variables.
Use function like this
Private Function CreateDir(FldrPath As String)
Dim Elm As Variant
Dim CheckPath As String
CheckPath = ""
For Each Elm In Split(FldrPath, "\")
CheckPath = CheckPath & Elm & "\"
If Len(Dir(CheckPath, vbDirectory)) = 0 Then
MkDir CheckPath
Debug.Print CheckPath & " Folder Created"
End If
Debug.Print CheckPath & " Folder Exist"
Next
End Function
then call it
Example
'Define Final Path
myFinalPath = myPath + Format$(NextFriday, "yyyy-mm-dd") + "\" + JobArea + "\"
CreateDir myFinalPath ' <--- call call function
According to my search, fdObj.FolderExists() can accept variables, like this:
Sub Test_File_Exist_FSO_Early_binding()
'If you want to use the Intellisense help showing you the properties
'and methods of the objects as you type you can use Early binding.
'Add a reference to "Microsoft Scripting Runtime" in the VBA editor
'(Tools>References)if you want that.
Dim FSO As Scripting.FileSystemObject
Dim FilePath As String
Set FSO = New Scripting.FileSystemObject
FilePath = "C:\Users\Ron\test\book1.xlsm"
If FSO.FileExists(FilePath) = False Then
MsgBox "File doesn't exist"
Else
MsgBox "File exist"
End If
End Sub
Reference from:
Test if Folder, File or Sheet exists or File is open
You could save and rename attachment refer to the below link:
Save attachments to a folder and rename them
I am trying to open a pdf file through MS Word, perform certain action such as evaluating calculations, printing the files, etc. and then proceed with closing the file. The error message I received is "Microsoft Excel is waiting for another application to complete an OLE action."
I have previously tried hyperlinkfollow and Shell MyPath & " " & MyFile, vbNormalFocus method, it doesn't work. I am still at the starting phase of opening the pdf files, please advice. Thanks!
Sub Extract_PDF_Data()
Dim mainData As String
Dim strFile As String
Dim Oldname As String
Dim Newname As String
Dim Folderpath As String
Dim s As String
Dim t As Excel.Range
Dim wd As New Word.Application
Dim mydoc As Word.Document
Folderpath = InputBox("Folder path: ")
Folderpath = Folderpath & "\"
strFile = Dir(Folderpath & "", vbNormal)
Do While Len(strFile) > 0
Oldname = Folderpath & strFile
Set wd = CreateObject("Word.Application")
Set mydoc = Word.Documents.Open(Filename:=Oldname, Format:="PDF Files",
ConfirmConversions:=False)
mainData = mydoc.Content.Text
mydoc.Close False
wd.Quit
strFile = Dir
Loop
End Sub
Don't us the New keyword in the line that declares the object variable. This will "block" the object variable - it causes the error when the code laters tries to instantiate it. This method can work in VB.NET but not in VBA.
Do it more like this:
Dim wd As Word.Application
Set wd = New Word.Application. 'Or use CreateObject
I think a combination of those three sources will lead to the answer:
How to open a pdf with Excel?
How to extract data from pdf using VBA?
How to open and print a pdf using VBA?
I think it will be something like this:
Sub Extract_PDF_Data()
Dim mainData As String
Dim strFile As String
Dim Oldname As String
Dim Newname As String
Dim Folderpath As String
Dim s As String
Dim t As Excel.Range
Dim Appshell As Variant
Dim ap As String
Dim Browsedir As Variant
Dim f As Variant
Dim KeyWord As String
' This is a suggestion, I use it because it is more convenient than copy-pasting folder paths
Dim FSO As Object
Set FSO = CreateObject("Scripting.Filesystemobject")
' Get Folder over user input
Set Appshell = CreateObject("Shell.Application")
Set Browsedir = Appshell.BrowseForFolder(0, "Select a Folder", &H1000, "E:\Xample\Path")
' check if not cancalled
If Not Browsedir Is Nothing Then
Folderpath = Browsedir.items().Item().Path
Else
GoTo Quit
End If
KeyWord = "The_Materialist_Example"
' go through all files in the folder
For Each f In FSO.GetFolder(Folderpath).Files
' if file is a pdf , open, check for keyword, decide if should be printed
If LCase(Right(f.Name, 3)) = "pdf" Then
' Here the methods suggest different answers.
' You can either use FollowHyperLink or use the Adobe Library to OPEN PDF
' I would write a function that checks the active pdf for the keyword : IsKeyFound
Debug.Print Folderpath & "\" & f.Name
Call PrintPDF(Folderpath & "\" & f.Name)
If IsKeyFound(f, KeyWord) Then
f.Print
End If
End If
Next f
Quit:
End Sub
Private Sub PrintPDF(strPDFFileName As String)
Dim sAdobeReader As String 'This is the full path to the Adobe Reader or Acrobat application on your computer
Dim RetVal As Variant
sAdobeReader = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"
'Debug.Print sAdobeReader & "/P" & Chr(34) & strPDFFileName & Chr(34)
RetVal = Shell(sAdobeReader & " /P " & Chr(34) & strPDFFileName & Chr(34), 0)
End Sub
Private Function IsKeyFound(PDF As Variant, KeyWord As String) As Boolean
'Decide if file needs to be printed, insert your criteria and search algorithm here
End Function
I have not been able to figure out how to extract the keywords, you could however use a user input as a first approach and later move on to a automated scan of the pdf.
I hope this gets you further on the way to the solution.
I am working on editing some code that was written by someone else and I have had very little Excel Macro experience. I am attempting to save a file to a network location after the code completes. The person who made this program had it being saved to the wrong location and didn't have it checking if the Folder exists or not.
This is what I currently have for grabbing the file for formatting...
It needs to grab the variable file name &MA&.txt from this location...
C:\Twist Check Vaules\&MS& &MP&\$MA%.txt
For example, if MS = TEST and MP = GO and MA = A then...
C:\Twist Check Vaules\TEST GO\A.txt
[Formats File]
Then at the end it needs to check to see if there is already a folder with the same name as the variables above but in a separate location...
Ex. Check for this folder...
O:\diaph\sdata\Blinglet\&MS& &MP&
For example, if MS = TEST and MP = GO...
O:\diaph\sdata\Blinglet\TEST GO
If this folder exists it needs to keep moving on, if not it needs to create it.
Then finally the file by the name of $MA$.txt or using the example, A.txt needs to be saved in that location...
O:\diaph\sdata\Blinglet\TEST GO
I tried looking this up myself but I have been having a lot of trouble since I am so new to excel macro. Any help would be much appreciated!
Sub Polywork_Formating_Macro()
MsgBox ("Polyworks Data Formatting: Autostart Macro in Excel")
Dim idx As Integer
Dim fpath As String
Dim fname As String
Dim MS As String
Dim FileTitle As String
Dim MP As String
Dim MA As String
Dim question As Variant
MS = InputBox("Enter Shop Order:", "File Name")
MP = InputBox("Enter Job Number:", "File Name")
MA = InputBox("Enter A, B , or 360:", "File Name")
FileTitle = " " & MA & ".xls"
idx = 0
fpath = "C:\Twist Check Values\" & MS & "\" & MP & "\" & MA & "\"
fname = Dir(fpath & "*.txt")
While (Len(fname) > 0)
idx = idx + 1
Sheets.Add.Name = fname`enter code here`
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" _
& fpath & fname, Destination:=Range("A2"))
.Name = "a" & idx
[
FORMATTING CODE IN THE MIDDLE REMOVED
]
ActiveWorkbook.SaveAs Filename:="O:\diaph\sdata\Blinglet\" & MS & "\" & MP & "\" & FileTitle & ""
question = MsgBox("Are There AnyMore Files To Be Formated?", vbYesNo)
If question = vbYes Then
Workbooks.Open "C:\Stage Formatter.xlsm"
End If
End Sub
For you file path and name you need double quotes around the strings.
Dim strFilePath as string
str = "C:\Twist Check Vaules\" & MS & MP & "\" & MA & ".txt
For you filesystem functions you will need to reference the library. In the VBA IDE go to the tools menu and select references. Select "Microsoft scripting runtime".
Then you can declare a filesystemobject. That can be used for you folder and file functions.
Dim fldr As Object
Dim strFolder as string
Dim fs As FileSystemObject
Set fs = New FileSystemObject
strFolder = "C:\Twist Check Vaules\" & MS & MP & "\"
If fs.FolderExists(strFolder) = true Then
'Do nothing
else
msbbox ("Folder is missing")
'or you can create it
Set fldr = fs.CreateFolder(strFolder)
If fldr Is Nothing Then
MsgBox "Could not create the folder"
End If
End if
For your text file:
Dim ts As TextStream
Set fs = New FileSystemObject
Set ts = fs.CreateTextFile("C:\Temp\test.txt", True, False)
ts.WriteLine "Whatever text you are writing to the file."
'Clean up
ts.Close: Set ts = Nothing
Set fs = Nothing
I've been trying to find a script that saves attachments to a folder on our network from Outlook. I've finally got something working but it looks like it doesn't work on my 2nd system which happens to be Outlook 2010. I can't say for sure if it's because of this difference.
Code is:
Sub SaveAllAttachments(objItem As MailItem)
Dim objAttachments As Outlook.Attachments
Dim strName, strLocation As String
Dim dblCount, dblLoop As Double
strLocation = "C:\test\"
On Error GoTo ExitSub
If objItem.Class = olMail Then
Set objAttachments = objItem.Attachments
dblCount = objAttachments.Count
If dblCount <= 0 Then
GoTo 100
End If
For dblLoop = 1 To dblCount
strID = " from " & Format(Date, "mm-dd-yy") 'Append the Date
'strID = strID & " at " & Format(Time, "hh`mm AMPM") 'Append the Time
' These lines are going to retrieve the name of the
' attachment, attach the strID to it to insure it is
' a unique name, and then insure that the file
' extension is appended to the end of the file name.
strName = objAttachments.Item(dblLoop).Filename 'Get attachment name
strExt = Right$(strName, 4) 'Store file Extension
strName = Left$(strName, Len(strName) - 4) 'Remove file Extension
strName = strName & strID & strExt 'Reattach Extension
' Tell the script where to save it and
' what to call it
strName1 = strLocation & "PDF\" & strName 'Put it all together
strName2 = strLocation & "JPG\" & strName 'Put it all together
' Save the attachment as a file.
objAttachments.Item(dblLoop).SaveAsFile strName1
objAttachments.Item(dblLoop).SaveAsFile strName2
Next dblLoop
objItem.Delete
End If
100
ExitSub:
Set objAttachments = Nothing
Set objOutlook = Nothing
End Sub
It doesn't matter what Outlook version you are using at the moment. The code should work correcly.
Possible reasons why it doesn't work:
I'd suggest choosing another location for saving files. The C: drive requires admin privileges on latest OS.
The rule is not triggered.
An error in the script. Try to call the script manually from other VBA sub and see what happens under the hood. Do you get any errors in the code?