VBA Save a String across submodule calls - vba

I am making an "intelligent save" button for word and excel files.
The first time it is run from a file, it will prompt user to navigate to the correct folder. The important part is the selected path will be saved for that file and automatically referenced the next time someone uses the macro. Then the user can specify pdf vs. docx/xlsx file type, then save the file.
Is the bolded part possible, and what kind of technique/functions can I use to do this?

Posted as an answer, with a bit of example code and more detail:
For such a small amount of data, why not use VBA's SaveSetting/GetSetting commands to put the needed info in the registry?
Sub SaveGetSettingExample()
' Saves string values to:
' HKEY_CURRENT_USER\Software\VB and VBA Program Settings\AppName
SaveSetting "AppName", "Section", "Key", "Value"
' Displays the just-stored value: Value
MsgBox GetSetting("AppName", "Section", "Key", "Default Value")
End Sub

I'm assuming you're embedding the code in the workbook (and not in the Personal code folder). If so, I've had success writing the file path to a cell in a hidden column (usually out to far right of view) in Excel. Your code can reference this default location as needed when loading the next time.
I'm not sure about Word, our Word documents stay pretty simple.

Related

VBA: Add to a UserForm's Title with current text already as caption

Good Evening,
I am having trouble with some VBA code. I need the add the Userform's Caption, with text already in place. This is for a application I'm writing which opens a file, and once the file has been opened, it will add the file name to the end of the UserForm's caption. For example:
Program Name: [File Name]
I wouldn't where to start really, which is why I'm here, but I think it might be something like
UserForm1.caption = "Program Name" + file.name
I don't know if this is really possible, but I would greatly appreciate some help
Cheers
Yes it' possible. I think a couple more steps needed
On open of application
logic example / not code:
Pub WriteFileName ()
Range("A:10")
End Sub
For the above, adaptable code example here : How to extract a file name from its path in vba
Then write another macro reading that cell range as string
to your UserForm.Caption object i.e ="string" + range.("A10")

Preserve settings in the file

I am creating my excel add-in that saves the current file as csv into user-specified folder. I would like my program to ask for the folder path the first time the program is launched and to remember that folder in the future. I am wondering is there any way to preserve the data within the program? I figured that I could write the path into .txt-file but that feels a little hack-like solution and would clutter the addin folder.
I use the GetSetting and SaveSetting functions in my VB 6 apps. Rather than cover them in detail, take a look at this excellent web page that illustrates how to use in with Excel
Excel Tips From John Walkenbach
Create a Worksheet, and store the values in cells. Then in the VBA Editor find the Worksheet in the Project Explorer (Ctrl + R) and set "Visible" to "2 - xlSheetVeryHidden" in the Properties Pane (F4) so that it is not readily visible to users.
You can then set/retrieve the data in with code in the format SheetName.Cells(row,column).Value, e.g.
MyPath = Sheet1.Cells(1,2).Value 'Get data from cell B1
Sheet1.Cells(2,2).Value = NewPath 'Set data in cell B2
There are multiple ways to approach this. Besides the hidden sheet approach, already described, you can
Write the information to a CustomXMLPart. This is a xml file stored in the workbook's ZIP file where information can be stored.
For something as short and simple as a file path, you could also use a CustomDocumentProperty

VBA Word - Save As dialog with initial filename

I have a vba macro that makes some changes to the current document and determines a filename that should be used for it - if the document isn't saved as that filename yet the user should be prompted to do so (but should be able to alter the default setting).
I found two possibilities that both are not perfect (I'd need a mix of those two).
First approach:
Application.Dialogs(wdDialogFileSaveAs).Show
Opens the Save As dialog and lets you change the format and name of the file, but the default file name is the old filename or the title (up to the first special character like blank or -) of the document (in case it wasn't saved yet - changing the title of the document is of little help as the suggested filename will contain -). Is it possible to change the initial filename shown in the Save As dialog?
Second approach:
Application.FileDialog(msoFileDialogSaveAs).InitialFileName = filename
Dim choice As Integer
choice = Application.FileDialog(msoFileDialogSaveAs).Show
If choice <> 0 Then
filename = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
Call ActiveDocument.SaveAs(filename:=filename, FileFormat:=wdFormatDocumentDefault)
End If
The FileDialog will choose a filename only, so we have to save it explicitely.
This approach will show the filename I want, but if the user changes the suffix to e.g .pdf the file will still be saved in the .docx format (using the suffix .pdf). I didn't plan to have huge distinction of cases here for the rare case the user needs a different format than .docx. Is there an easy way to save the file in the correct format using this second approach?
Have you tried replacing the Call ActiveDocument.SaveAs line with
Application.FileDialog(msoFileDialogSaveAs).Execute
Window's setting "View tab - File name extension" maybe affecting this.
Turn it on to see if it will fix it.

In batch file, how to get focus on a specific window (opened file)

A very simple question I suppose, but I reached a deadlock with this:
I have to use a .bat file to imput plain text data into the right cells an excel sheet with lots of graphics content, vba parts, macro that deactivate "normal" EXCEL buttons and functions, password to protect the pre-typed functions, sudden and unexpected changes in the version of the "taget file", and many other complications...
My need is to be absolutely sure that the .bat is sending the sequence into the right version of the .xlsm file.
To do that I want to store the last known filename (that include the file version) in the .bat file, and I want to take focus on the excel window in wich the data have to be written ONLY IF the title of the excel window is exactly the same.
So Here is the question: How to get the focus on a specific open file from a .bat file?
You can't. If you wanted to use vbscript or jscript you could do what you want in a command prompt in an unreliable way (but it will work most circumstances).
Excel has it's own forms.
Put column headers in a row. Put selection in same row. Alt + D, O.
Plus you can make Excel only allow entries on some cells, like a invoice form.
Right click cell, Properties, Protection, Unlock. Then Alt + T, P, P.
Word has it's own forms similar to Excel (Word is also a spreadsheet).
Excel VBA language (and VBScript too) has input box command.
Sub main()
Sheet1.Range("A1").Value2 = InputBox("enter Value")
End Sub

macro to return active document format for IF/Then statement

I am creating a document template for a report for my staff to use and I have a command button at the bottom that will delete all of the command buttons in the report and protect it as read only to close out the report.
I don't want someone accidentally making these changes to the template if they happen to open that instead of a new document based on it.
So I would like a string of code that checks the active document, if it is .dotm I want it to display a message box and exit. if it is a .docx I want it to continue with the rest of the code I have written.
I have been unable to return the format or use it in an IF/THEN statement. I have been unable to find anything on the net on this either. Is it impossible? or should I be checking for the file extension? If so how would I use that as a value in an IF/THEN Statement?
The document may have been based on the template, but not yet saved. In which case it would be called "Document1", etc., without a dot.
If InStr(ActiveDocument.Name,".") = 0 Then
'it is a new document, based on a template
ElseIf InStr(ActiveDocument.Name,".dotm") > 0 Then
'it is a/the template
This of course assumes that the ActiveDocument is the correct one. If they click a button in the document then this is correct, but if they use the Macros dialog then you may want to include additional checks.
I would use the following, which ignores differences in case (.dotm, .DOTm):
If InStr(UCase(ActiveDocument.Name), ".DOTM") > 0 Then
'it is a template..
Else
'it's just a document
End If
Checking ActiveDocument.AttachedTemplate.Name can also be useful, to confirm if the active-document is one based on your template.