How can I get the disk path of a word document using VBA? Document.Path returns the web path instead - vba

I have a word document with some vba code. I want to return the path of the directory in which the word document is saved.
This is the code I used:
Dim PathCurrentDocument As Variant
PathCurrentDocument = ActiveDocument.path
Debug.Print PathCurrentDocument
The desired output is:
"C:\Users\firstname.lastname\OneDrive - company name\VBA\4_update_documents_with_vba_inside_word\document_templates_to_modify"
What I am getting, is the web link, which looks like this:
https://my-company.sharepoint.com/personal/my_name/Documents/VBA/4_update_documents_with_vba_inside_word/Document_A_Template_with_macro.docm
The microsoft documentation only says the property returns the disk or web path to the document. It does not say how to choose which one to return.

Depending on where the document is coming from the Document.Path property returns the disk or Web path to the document.
Use the Document.SaveAs2 method if you want to get a local file path. Basically, you need to save the file on the hard drive anywhere.

Related

VB.NET open a Text File within the same folder as my Forms without writing Full Path

I found a similar question but it was 5 years 8 months old, had 2 replies and neither worked for me (VB.Net Read txt file from current directory)
My issue is that when I use the following code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Username_And_Password_Raw.txt")
Dim usernameAndPassword = Split(fileReader, ",")
I get an error saying:
System.IO.FileNotFoundException: 'Could not find file 'C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows\Username_And_Password_Raw.txt'.'
I have tried using all the different Applications.BLANKPath options I can find (ie; StartupPath, CommonAppDataPath, etc.) and they all return essentially the same error only with a different location.
This is the folder layout of my TXT File - I know it's a terrible, incredibly insecure and generally awful way of storing login information but this is just for a NEA so will never ever actually be used
This is the actual path of the TXT File if it helps
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\Username_And_Password_Raw.txt
The startup path is where your exe is located. That and all supporting files get copied to a binary directory when you compile in visual studio, in your case
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows
But what you're trying to do, reference the file where it sits in your solution, is probably not the best way to do it, and your code above will work (with a change, will mention later) if you change the properties of the file in the solution.
Right click on the file in the Solution Explorer Username_And_Password_Raw.txt, select Properties. Modify Copy to Output Directory to either Copy always / Copy if newer, depending on your requirement. Now that file will copy to the same directory your exe is in, and the code above should work.
Note, when creating a path, don't use string concatenation because you may have too many or too few \; use Path.Combine:
Dim filePath = Path.Combine(Application.StartupPath, "Username_And_Password_Raw.txt"
Dim fileContents = My.Computer.FileSystem.ReadAllText(filePath)

Word VBA Documents.Open deleting files in folder when falsely passing that folder's path instead of file path

I encountered the following issue:
When accidentally passing a folder path to the Documents.Open function in VBA Word I get the runtime error 5174 as one would expect.
However all files with names that begin with an underscore get deleted in that moment from that folder.
To replicate:
Assume folder C:/Test/
In said folder have two files:
test.txt
_test.txt
In Word VBA execute the command:
Documents.Open("C:/Test/")
(As part of a subroutine or in the immediate window.)
Result: Runtime Error 5174 and _test.txt is now missing.
Note: Passing a nonexisting file like "C:/Test/abc.txt" or a wrong folder path like "C:/Test" (without the last slash) will not have this effect and won't cause the runtime error.
I have only tested this on one system on a network drive under windows 10 with Microsoft Professional Plus 2019. It's entirely possible that it's an issue with the file system. Does anyone have any suggestions as to why is this happening? I now included the workaround to check if I'm passing a folder, but it's still unnerving.
The Documents.Open method opens the specified document and adds it to the Documents collection. It is designed to take the file path, not a folder. If you want to allow users to pick file(s) you may consider using the file open dialog. The FileOpenDialog triggered by your code which opens a folder for picking files allows specifying file formats that should be supported and visible via the dialog window.
Set dlgSaveAs = Application.FileDialog(msoFileDialogFilePicker)
dlgSaveAs.Filter = "Text Files (.txt)|*.txt|Word Documents (.docx)|*.docx|Word Template (.dotx)|*.dotx|All Files (*.*)|*.*"
dlgSaveAs.ValidateNames = true
Res = dlgSaveAs.Show

VBA store path including Environ("username") in a text file

I am trying to create a text file that stores a folder path. This text file is then referenced via a vba sub. The path I want to use is something like:
"C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Templates"
This works fine in the sub but I've tried all kinds of variations in the text file but none of them get recognised and trigger error 52 - bad file.
Is there a way to make this work? I'm trying to allow people to set a different file path without needing to modify the code.
If you are trying to provide a path to the folder where user templates are stored then you could try
ActiveDocument.AttachedTemplate.Path
as an alternative (returns the path to the folder where the current template is stored for the user).
Otherwise store the path template as something like
"C:\Users\###UserName###\AppData\Roaming\Microsoft\Templates"
Which gives you a single string to retrieve. Then you can use the VBA Replace function to change the ###UserName### to the value of Environ("UserName)"
my_user_path = replace(my_path_template, Environ$("UserName"))
You might also want to explore using either a CustomDocumentProperty, or a Variables, to store your path template as this keeps the path template string as part of the Document or Template and not in a separate file.

VBA code (if needed) to save new Word document in same directory as other Word doc

Many users, myself included, begin editing a Word document, create a new Word doc, and wish to save the second doc in the same directory as the first doc. This is the default behavior in an editor such as emacs. Word 2013, alas, makes me pick the directory ("Folder") where I wish to save the new file, forcing me to select among various network folders and then select multiple subdirectories before I reach the one containing my first document. I used to have a simple VBA script that would find the directory of the first file and then save the new file in that directory, or at least it would set the directory of the first file as the default directory for saving files. Does anyone have code to do what I'm looking for? Thanks!
This will the working directory to the directory of the first file you were working on:
ChDir(Application.Documents(Application.Documents.Count).Path)
If you want to save the most recent opened document to the same location as the first file you were working on, then try the following
Sub SaveWithFirstFile()
NewFileName = "filename1.docx
Application.Documents(1).SaveAs2 FileName:=Application.Documents(Application.Documents.Count).Path & "\\" & NewFileName
End Sub
Change "filename1.docx" to what you want it to

Capture only the file path from the file upload control

I am trying to update some local access databases from a web database. When I am accessing the web page, I want the user to select a folder on the local hard drive where the DB's reside that will be updated by the program. I actually have been using the File Upload control to do this as it has allowed me to check the file extensions on the local DB's their file size and other misc. items.
This captures the full path with the file name...
fileName = FileUploadAccess.PostedFile.FileName.ToLower
Now I have a need to capture the full path of the db's on the local hard drive. I can get the full path with the filename, but then I need to write a bunch of code to strip the filename from the path variable.
Is there a simple way to capture the path of the location the DB when the file location is selected, something like this....
Dim thePath As String = System.IO.Path.GetFullPath
Thanks for any suggestions.
You can use IO.Path.GetDirectoryName
Here is a sample code:
Dim MyDirectoryPath As String = System.IO.Path.GetDirectoryName(MyFullPath)