How to set a specific default directory for a Save As operation in VBA - vba

We have a MS Access software which we need to be able to save a MS Word document from. It is not problem to get the save as dialog in word, using the VBA, but is it possible to get it to change the default directory to a path specified in the VBA? It just saves as on the desktop as default.
Edit: For the first answer:

You can use Application.FileDialog to ask the user for a path to save to:
Dim ofd As Office.FileDialog
Set ofd = Application.FileDialog(msoFileDialogSaveAs)
ofd.Title = "Save As..."
ofd.InitialView = msoFileDialogViewList
ofd.InitialFileName = "c:\temp\myfile"
' Show Dialog and abort if user clicks cancel:
If (ofd.Show = 0) Then Exit Sub
MsgBox ofd.SelectedItems(1) ' shows the selected filename
Use that path to directly save the word document.

You can just add the filename you would like to the dialog as such:
Application.GetSaveAsFilename("c:\temp\myfile")
This will open the dialog in the temp folder and suggest myfile as name for the file.
See here for other modify-able stuff in the dialog: https://msdn.microsoft.com/en-us/library/office/ff195734%28v=office.15%29.aspx

Related

MS Word runs on background and requests documents to be saved even though it is already saved

I have a procedure that creates a PDF file according to an ms word template and its data is retrieved from a database.
It works fine, creates a PDF file perfectly , no run time errors. The problem is that whenever I shut off the computer, ms word prevents the shutdown and if I press cancel ms word shows a message;
The code goes like this;
Dim wordApp As Word.Application
Dim templateBookmarks As Word.Bookmarks
Dim templateName As String
Dim template As Word.Document
'Some other variables for computations
wordApp = CreateObject("Word.Application")
sourceTable = New DataTable
'Some other procs to fill the data table
templateName = "Foo Template.docx"
template = wordApp.Documents.Add(templatePath & templateName)
templateBookmarks = template.Bookmarks
templateBookmarks.Item("sample bookmark").Range.Text = "foo"
'Then fills the table in the template like...
template.Tables(1).Cell(1, 1).Range.Text = dataSource.Rows(0).Item(0)
'Then saves the document as a pdf
Dim saveName As String = "sample file"
template.SaveAs2(savePath & saveName, Word.WdSaveFormat.wdFormatPDF)
I have tried to force garbage collection for the word COM resources, as well as changing the template from an actual document i.e. docx to a word template .dotx. I also tried the method Quit() but it only shows the ms word message much earlier. This is the first time I needed to use interop so pardon if I don't have much idea about it.
The files I needed are saved, the only problem is the ms word message and unsaved and unnecessary files e.g. Document1,Document2,Document3 that seems to be created aside from the required PDF
Use the Document.Close method which closes the specified document after saving files using the PDF file format. It allows specifying the SaveChanges parameter which specifies the save action for the document. Can be one of the following WdSaveOptions constants: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges.
On Error GoTo errorHandler
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
errorHandler:
If Err = 4198 Then MsgBox "Document was not closed"

VBA: Get Excel FileDialogOpen to point to "My Computer" by default

I'm trying to get excels save and open dialog boxes to open to "my computer" by default so the user can select a drive from there.
I have got the dialog boxes to open to any path on any drive or my documents etc but can't seem to find a way for it to open to my computer.
This is the code i'm using at the moment and it works fine for a known path:
MsgBox objFolders("desktop")
ChDrive objFolders("desktop")
ChDir objFolders("desktop")
strFileName = appRemoteApp.Workbooks("Export Template.xlsm").Application.GetSaveAsFilename(objFolders("desktop") & "\Replica Export " & UserName & " " & Format(Date, "yymmdd") & ".xlsm", FileFilter:="Excel Macro Enabled Workbook (*.xlsm), *.xlsm,")
Also, I have found this from this site.
If you paste ::{20D04FE0-3AEA-1069-A2D8-08002B30309D} into windows explorers address bar it takes you to my computer but if I use this in my VBA code
ChDir "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
it says it cant find the directory or something. So not sure if there is a work around for this or something.
This did not work either:
ChDir "C:\WINDOWS\explorer.exe /root,,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
The reason i'm wanting to have the dialog boxs open to computer is that we will be hosting the excel doc on a windows server with access though RemoteApp and remote desktop. The users will not have access (rights) to the servers drives and folders etc, they will only have access to their own drives on their local machines which will be mapped and are visible under the servers "My Computer" folder for lack of a better word. The master document on the server generates a replica using VBA code and is then saved to the users local hard drive.
AFAIK there is no pure VBA solution to override the original behaviour. You can use an alternative from Robert Mearns answer but it doesn't show the windows form so it's less customizable.
Follow this answer if you want to achieve the exact effect - FileOpenDialog.
You can print all the environmental variables using the Environ$() function. This will not show any variable directly pointing to MyComputer therefore you can't pass it to the .InitialFileName property.
MyComputer is not a physical location that you can access through cmd. I think of it as an abstract Interface and it's quite difficult to explain how VBA and .InitialFileName uses a string to access a location.
Well, the only workaround the problem I can think of it's to use an external library written in for example C# that can access the MyComputer.
It's easier than it sounds!
Follow the below steps to create your Custom OpenFileDialog.
You need a Visual Studio Express For Desktop - it's free to download and use.
After installation - run as Administrator! (it's necessary for the libraries to get registered)
Select File and New Project. Rename it to CustomOFD and and hit the OK.
Right-click the CustomOFD Project in the Solution Explorer and Select Add References
Add references to the System.Windows.Forms as shown in the below img
Right-click Class1.cs in the Solution Explorer and rename it to CustomOFD.cs.
Double click your CustomOFD and replace the code with the one from below
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CustomOpenFileDialog
{
[InterfaceType(ComInterfaceType.InterfaceIsDual),
Guid("541EDD34-4CDC-4991-82E9-6FC23F904B5B")]
public interface ICustomOFD
{
DialogResult ShowDialog();
string FileName();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("E33102F0-B3C0-441C-8E7A-B9D4155A0D91")]
public class CustomOFD : ICustomOFD
{
private OpenFileDialog box = new OpenFileDialog();
public CustomOFD()
{
box.Multiselect = false;
box.Title = "Select file";
box.InitialDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}";
}
public DialogResult ShowDialog()
{
return box.ShowDialog();
}
public string FileName()
{
return box.FileName;
}
}
}
Note: you can generate a new GUID for your own class using the Tools => Create GUID and replace it with your own, if you wanted to...
Right-click the CustomFileOpenDialog in the Solution Explorer and select Properties
In the Properties window go to Application tab and click Assembly Info and tick the Make COM-Visible box
Then go to the Build tab and tick Register for COM interop
Right-click the project and select Build from the menu
Now look in the Output tab as it shows you where the library was compiled to
usually its
c:\users\administrator\documents\visual studio 2012\Projects\CustomOpenFileDialog\CustomOpenFileDialog\bin\Debug\CustomOpenFileDialog.dll
Ok. Now save and close VS.
Open Excel and go into VBE ALT+F11 and insert a standard module
Click Tools on the menu bar and select References
Click the Browse button and navigate to the CustomOpenFileDialog.tlb file and click OK add to the list of references
Copy paste the code for module
Option Explicit
Sub Main()
Dim ofd As New CustomOFD
Set ofd = New CustomOFD
ofd.ShowDialog
Debug.Print ofd.Filename
End Sub
finally, run the sub and enjoy the computer as the default location for the customized OpenFileDialog box!
I cannot see a way to use the GetSaveAsFilename or similar dialogs to open on Computer or My Computer.
It is possible to prompt the user to select a folder using VB Script.
The root displayed is Computer and the user can select a folder.
The file can then be saved to the selected folder programatically.
Sub Test()
MsgBox BrowseForFolder(MyComputer)
End Sub
http://technet.microsoft.com/library/ee176604.aspx
Function MyComputer() As Variant
Dim objShell As Object, objFolder As Object
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(&H11&)
MyComputer = objFolder.self.Path
Set objShell = Nothing
Set objFolder = Nothing
End Function
http://www.vbaexpress.com/kb/getarticle.php?kb_id=405
Function BrowseForFolder(Optional OpenAt As Variant) As Variant
Dim ShellApp As Object
Set ShellApp = CreateObject("Shell.Application"). _
BrowseForFolder(0, "Please choose a folder", 0, OpenAt)
On Error Resume Next
BrowseForFolder = ShellApp.self.Path
On Error GoTo 0
Set ShellApp = Nothing
End Function
.InitialFileName = "Computer"
Works for me with FileDialog(msoFileDialogFolderPicker)
Tested on Windows Vista - Excel 2007

How to stop a Word Document immediately when newly created

I have a VS2010 Vb.net program that creates a Word 2007 file.
My Normal.dot file is customised to give me a new Tab with Buttons in that do specific things via VBA in the Normal.dot program when those Buttons are pressed.
This all works fine, however, I now want to add some functionality whereas as soon as the new Word document is created, it edits a Task in Outlook.
I have edited the 2 "This Document" Procedures and you can see my Normal.Dot file in the attached Screenshot.
When I run my VB.Net program to create a brand new Word 2007 document, the program does NOT stop on either of the message boxes, it just continues and opens the Word document as before, my code is below, what am I doing wrong ?!?
'Open or Create Word document for Editing
myNewsLetter = myFolder + myLeague + "News" + mySession + ".doc"
If File.Exists(myNewsLetter) Then
'do nothing
Else
myTemplate = myTempFolder + "NL Skeleton.doc"
File.Copy(myTemplate, myNewsLetter)
Create_Blank_Newsletter()
End If
'Open Word Newsletter, or switch to it if it's already open
Dim myFileOpen As Boolean
myFileOpen = IsFileOpen(myNewsLetter)
If myFileOpen = False Then
MSDoc = MSWord.Documents.Open(myNewsLetter)
End If
MSWord.WindowState = Word.WdWindowState.wdWindowStateNormal
MSWord.Visible = True
MSWord.ActiveDocument.Bookmarks("\StartOfDoc").Select()
OK, sorted this, the full discussion can be found here ... http://www.vbaexpress.com/forum/showthread.php?p=286771#post286771
Basically, I'm not creating a NEW document, I am creating a new document via a Copy and then opening that existing document !!!

how to open selected files through the default application of the file in VB 2010?

I have Windows application written in VB 2010.Here, user may select any file from open dialog.So, I want to open the file in corresponding application.for example, suppose user selecting docx file then i have to open the file using msword,suppose,if it is a pdf file, then i have to open with adobe reader or available pdf reader(default application).
Is this possible to do?
Shell and the Windows API CreateProcess() are for starting executable files.
If you're loading a document/file then these are handled by ShellExecute() and can be initiated in .NET using the Process.UseShellExecute property:
Private Function ShellExecute(ByVal File As String) As Boolean
Dim myProcess As New Process
myProcess.StartInfo.FileName = File
myProcess.StartInfo.UseShellExecute = True
myProcess.StartInfo.RedirectStandardOutput = False
myProcess.Start()
myProcess.Dispose()
End Function
Taken from the #VB wiki.
Try this:
now with openfiledialog
Dim OpenFileDlg as new OpenFileDialog.
OpenFileDlg.FileName = "" ' Default file name
OpenFileDlg.DefaultExt = ".xlsx" ' Default file extension
OpenFileDlg.Filter = "Excel Documents (*.XLSX)|*.XLSX"
OpenFileDlg.Multiselect = True
OpenFileDlg.RestoreDirectory = True
' Show open file dialog box
Dim result? As Boolean = OpenFileDlg.ShowDialog()
' Process open file dialog box results
for each path in OpenFileDlg.Filenames
Try
System.Diagnostics.Process.Start(Path)
Catch ex As Exception
MsgBox("Unable to load the file. Maybe it was deleted?")
End Try
If result = True Then
' Open document
Else
Exit Sub
End If
next
This will work if the file is registered with the OS. Use Try catch because it can throw errors if the file is in use.
Edit: It uses always the default application.

VB.net Save File Dialogue error - Could not find special directory 'Desktop'

I have a fairly straight forward peice of code that just tries to set the default saved directory for a standard .net save dialogue to a specific folder. If that folder doesn't exist, it sets it to the desktop.
This works fine for everyone but one user who is getting the following error:
Could not find special directory 'Desktop'
How is that even possible?
'Check if folder exists
If Not IO.Directory.Exists(strDirectory) Then
strDirectory = FileIO.SpecialDirectories.Desktop
If Not IO.Directory.Exists(strDirectory) Then
strDirectory = IO.Directory.GetCurrentDirectory
End If
End If
'Show save file dialogue.
Dim folderDlg As New Windows.Forms.FolderBrowserDialog
folderDlg.RootFolder = Environment.SpecialFolder.Desktop
folderDlg.SelectedPath = strDirectory
folderDlg.ShowNewFolderButton = True
How about:
strDirectory = _
Environment.GetFolderPath(Environment.SpecialFolder.Desktop).ToString()
I use GetFolderPath() to get "My Documents" and it works fine (I don't ever have to think about it).