How to change the name of the document in Excel? - vba

I have a Macro Enabled Template called TIP-PBI.xltm. When I create a document based on this template, Excel automatically names it TIP-PBI1. However, I want to give it a custom name.
I figured I could do that by modifying the .Title property of the Workbook. To that end, on startup the Workbook_Open event kicks off, and the following is executed:
Private Sub Workbook_Open()
Dim strPBI As String
strPBI = InputBox$("Enter PBI", "Enter PBI")
ThisWorkbook.Title = "TIP-PBI-" & strPBI
End Sub
However, this does nothing.
How can I change the Title of the document on startup?

the only way to change the workbook name is to save it (ref) so you could do something like
ThisWorkbook.SaveAs ThisWorkbook.Path & "" & FileName & ".xls"
if you only want to suggest a name then you could use GetSaveAsFilename or
Application.FileDialog(msoFileDialogSaveAs).InitialFileName = ThisWorkbook.Path & "" & FileName & ".xls"

If the new workbook is created from a template then it takes the template name. Hence in instances where I wish to set the name of the new work book I copy a dummy template to the required name and then open the new workbook based upon the renamed template.
strFile = "C:\Temp\" & strnewname & ".xltx "
FileCopy "C:\Temp\Dummy.xltx", strFile
'Open template to new workbook
Workbooks.Open Filename:=strFile
Kill strFile 'delete renamed template

Related

VBA Open File From This Workbook's Folder Knowing Part of The Name

I am trying to open file from the same folder as the main workbook. The problem is that the name is not permanent and just one word stays always inside the name - "NAME".
I want to use specific method with Thisworkbook.Path to open the xlsx file but it is not finding the workbook with the code.
that is the relavant part of code:
Sub RemoveDuplicats()
Dim Harel As Workbook
Dim SAP As Workbook
Dim Path As String
Dim Found As String
Path = ThisWorkbook.Path
Found = Dir(Path & "*NAME*.xlsx") 'open SAP report
If Found <> "" Then
Set SAP = Workbooks.Open(Path & Found)
End If
End Sub
ThisWorkbook.Path Returns the path without trailing backslash,
try
Found = Dir ( Path & "\" & "*NAME*.xlsx")
You would need to Loop though all Fiels in this Folder and compare the File Names like this:
Dim StrFile As String
StrFile = Dir(ThisWorkbook.Path & "\*" & ".xlsm")
Do While Len(StrFile) > 0
If StrFile Like "*Name*" Then
MsgBox StrFile 'This will be your File
End If
StrFile = Dir
Loop

Excel VBA: Saving data/file to another format without macro

I have this userform
It is fully fuctioning but I want to add a feature that is sending the file as .xlsx or .txt so I can remove the macro from the file.
I searched the internet for days and come up to a procedure that I need to make a 3 process to save it to another format. The process I come up is listed below:
1. .SaveCopyAs
Copy(Filename).(Same format)
.Open
Existing File
.SaveAs
(FileName).(Any format)
And delete the SaveCopyAs file to avoid redundancy Or catch the temporary file to SaveAs another file format? Every input should be save after clicking ok button and to overwrite the existing file.
Can someone tell me if I'm making the right approach to my problem? Thanks.
I have had a similar issue, my solution involved copying the Sheets into a new workbook then renaming them accordingly and saving that workbook with a specific name:
ans = MsgBox("Would you like to export the Report?", vbYesNo)
Select Case ans
Case vbYes
FPath = "C:\...\...\... Daily Report"
FName = "Report" & ".xlsx"
Set NewBook = Workbooks.Add
ThisWorkbook.Sheets("Sheet2").Copy Before:=NewBook.Sheets(1)
ThisWorkbook.Sheets("Sheet3").Copy Before:=NewBook.Sheets(1)
Application.DisplayAlerts = False
'NewBook.Sheets("Sheet1").Delete to delete the first empty sheet on the new workbook
If Dir(FPath & "\" & FName) <> "" Then
MsgBox "File " & FPath & "\" & FName & " already exists"
Else
NewBook.SaveAs Filename:=FPath & "\" & FName
End If
NewBook.Close False
CurrentReport = FPath & "\" & FName
Case vbNo
Exit Sub
End Select
Or to append the data to a text file, each time the user clicks "OK":
Sub VBA_to_append_existing_text_file()
Dim strFile_Path As String
strFile_Path = "C:\temp\test.txt" ‘Change as per your test folder and exiting file path to append it.
Open strFile_Path For Append As #1
Write #1, "This is my sample text" ' add entered data here
Close #1
End Sub

Excel Add-in changes the file name to the add-in`s name although it should not

I need your help regarding an add-in I created using VBA, then I saved as add-in to be able to use on all Excel workbooks and also send it to my friends.
The add-in simply saves the printed area in the active sheet as a PDF file with the same name of the workbook, it saves the PDF to the desktop and works fine as a macro.
But when I save as PDF and use it, it saves the PDF file with the same name of the add-in, not as the workbook`s name.
Any suggestions?
The VBA code is:
Sub Save_as_pdf()
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = "C:\Users\" & Environ("UserName") & "\Desktop\" & ThisWorkbook.Name
If FSO.FileExists(ThisWorkbook.FullName) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=sNewFilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
End Sub
To elaborate on Matteo NNZ's comment above:
ThisWorkbook refers to the workbook in which the code is currently being executed from (in this case, the add-in)
ActiveWorkbook refers to the workbook that is currently active within the same instance of Excel.

Open Multiple Files from Variable location using VBA

I want to open 4 different Excel files saved under same folder using VBA code, but the folder path is not fixed.
Let's say, I have 4 Excel files named A.xlsx, B.xlsx, C.xlsx & D.xlsx under folder named 22-Feb-15 (This folder name will change everyday, but the file names will remain same).
I want VBA code so that I can select the folder manually and once it is selected, all 4 files will open one by one (there are other files too, but I need to open only these 4 files).
Please see below:
Sub FolderSelect()
Dim intResult As Integer
Dim fldrPath As String
intResult = Application.FileDialog(msoFileDialogFolderPicker).Show
If intResult <> 0 Then
fldrPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1)
Workbooks.Open Filename:=fldrPath & "\" & "A.xlsx"
Workbooks.Open Filename:=fldrPath & "\" & "B.xlsx"
Workbooks.Open Filename:=fldrPath & "\" & "C.xlsx"
Workbooks.Open Filename:=fldrPath & "\" & "D.xlsx"
End If
End Sub
You can change file names and/or add new files by following the same structure

Export As A Fixed Format Excel 2007

I have been assigned the task of developing a excel document that whole office will use. The user will click a button and the macro will export the file as a PDF to a shared folder. I wrote this code and tested this code using excel 2010. People that have excel 2007 where getting an error message saying "Run Time Error 1004 Document not saved. This document may be open, or an error may have been encountered when saving." I looked into the problem a little bit and found that excel 2007 needed an add-in update, so I installed it on their computers. I also checked to see if they have adobe on their computers and they do. They are still having the problem and I am unsure of what to do. Any help would be greatly appreciated!
Here is my code
' Define all variables
Dim strFileName As String
Dim folder As String
Dim member As Integer
Dim member_count As Integer
Dim member_name As String
Dim show As Variant
Dim MyTime As String
'Save as new file
Worksheets("Input data").Visible = True
folder = Sheets("Input data").Range("location").Value
MyTime = Time
Sheets("Input data").Select
Range("G2").Value = MyTime
strFileName = folder & "Material Request - " & Sheets("Input data").Range("name").Value & "_" & Sheets("Input data").Range("date").Value & " " & Sheets("Input data").Range("time").Value & ".pdf"
Sheets("Material Request").Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName 'OpenAfterPublish:=True`
You should start with changing the code to remove .Select & .ActiveSheet instances.
Dim oWS as Worksheet
Set oWS = ThisWorkbook.Worksheets("Input data")
' Worksheets("Input data").Visible = True
folder = oWS.Range("location").Value
If Right(folder,1) <> Application.PathSeparator Then folder = folder & Application.PathSeparator
MyTime = Time
' Sheets("Input data").Select
oWS.Range("G2").Value = MyTime
strFileName = folder & "Material Request - " & oWS.Range("name").Value & "_" & oWS.Range("date").Value & " " & oWS.Range("time").Value & ".pdf"
Debug.Print "strFileName: " & strFileName
'Sheets("Material Request").Select
oWS.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName 'OpenAfterPublish:=True`
Set oWS = Nothing
Refer to this MSDN Worksheet.ExportAsFixedFormat Method, you may need fill in more parameters depending on properties of the Worksheet "Input Data".
I have added some checks and refer to Immediate window to check value of strFileName in 2007.
I had a similiar problem (Error 1004 when attempting export). After an hour of pulling my hair out, here was the source of my problem.
I was passing a cell value as part of generating the filename. I was doing this in the format of
fileName:= ActiveWorkbook.Path & "\" & CStr(Workbooks.Cells(i,j).Value) & ".pdf"
The text in the cell itself was formatted to be in two rows (i.e. "top row text" + (Alt+K) + "bottom row text"). While the string looks normal in Debug.print, MsgBox, or value previews, I am thinking that there is a hidden character which encodes the new line for the cell. I believe this hidden character causes the error when passed as part of the fileName argument. I'm guessing Excel doesn't pick it up but the OS's file name system does.
In any case, this fixed the issue for me.