VBA Excel save .xlsx file with the flexible name - excel

I would like to save my file with the flexible name, which will change as the cell value changes.
The one answer is here:
Save a file with a name that corresponds to a cell value
however, I want also some fixed part of the name, which won't change unlike the part described in the query above.
Basing on this solution I tried to write something as follows:
Sub Save ()
Dim name As String, Custom_Name As String
name = Range("A2").Value
Custom_Name = "NBU" & name & "- Opportunity list.xlsx"
ActiveWorkbook.SaveAs Filename:=Custom_Name
In the effect, I am getting an error:
This extension cannot be used with the selected file type. Change the file extension in the File name text box or select a different type file by changing the Save as type.
I would like to have this file in the .xlsx extension.
Excel VBA - save as with .xlsx extension
The answer above doesn't really match to my situation.
It will be vital to remove all form control buttons in the newly saved file, when possible.
Thanks & Regards,
End Sub

There is no action in the routine listed to save the file. It just simply takes the contents of a cell and creates a string with wrapped values.
I am not totally sure of what your goal is, but you need to add the action from the second link you provided. Workbook.SaveAs Method.
See the code below for a working example that I created to test.
Public Sub Save()
Dim name As String, Custom_Name As String
name = Range("A2").Value
Custom_Name = ThisWorkbook.Path & "\" & "NBU" & name & " - Opportunity list.xlsx"
'Disable alert when saving
Application.DisplayAlerts = False
'Save the workbook.
ActiveWorkbook.SaveAs Filename:=Custom_Name, FileFormat:=51
End Sub
You should note that after this code has executed, you will now be in the newly created file. This is not an export.
Test this and let me know if you have any questions. There are a few things that seem to be unnecessary in your code, but we can address those if you find this answers your first issue.
Edit:
I would also call out specifically then worksheet with the range as well.
name = Worksheets("Sheet1").Range("A2")

You said the file name is 'Opportunity v1.0.xslm'. Would it have macros? My version of Excel complains about using .xlsx if there is code in the workbook.

Related

How to programmatically export and import code into Excel worksheet?

We will put 100s of Excel worksheets out in the field this year. The code periodically needs to be updated when bugs are found. For last year's effort, I was able to dynamically have workbooks pull updates for .bas files. This year I want to dynamically have workbooks pull updates for the code embedded in the worksheets too.
EXPORT CODE
The export code is pretty simple, but there are artifacts in the .txt files
Sub SaveSoftwareFile(path$, name$, ext$)
ThisWorkbook.VBProject.VBComponents(name).Export path & name & ext
Example Call: SaveSoftwareFile path, "ThisWorkbook", ".txt"
The problem is that the export has a lot of header information that I don't care about (in red). I just want the part in blue. Is there switch that allows me not to save it, or do I have to manually go into the export and remove it myself?
IMPORT CODE
The import code is pretty straight forward too, but it causes the error "Can't enter break mode at this time", and I'm struggling to figure out the right path forward. If I manually try and delete this code, Excel is also unhappy. So maybe my approach is altogether incorrect. Here's the code:
Sub UpgradeSoftwareFile(path$, name$, ext$)
Dim ErrorCode%, dest As Object
On Error GoTo errhandler
Select Case ThisWorkbook.VBProject.VBComponents(name).Type
Case 1, 3 'BAS, FRM
<Not relevant for this discussion>
Case 100 'Worksheets
Set dest = ThisWorkbook.VBProject.VBComponents(name).codemodule
dest.DeleteLines 1, dest.CountOfLines 'Erase existing | Generates breakpoint error
dest.AddFromFile path & name & ext '| Also generates breakpoint error
End Select
Example Call: UpgradeSoftwareFile path, "ThisWorkbook", ".txt"
Thanks in advance for your help
Please, try the next way of exporting and you will not have the problem any more:
Sub SaveSoftwareFile(path$, sheetCodeModuleName$, FileName$)
Dim WsModuleCode As String, sCM As VBIDE.CodeModule, strPath As String, FileNum As Long
Set sCM = ThisWorkbook.VBProject.VBComponents(sheetCodeModuleName).CodeModule
WsModuleCode = sCM.Lines(1, sCM.CountOfLines)
'Debug.Print WsModuleCode
strPath = ThisWorkbook.path & "\" & FileName
FileNum = FreeFile
Open strPath For Output As #FileNum
Print #FileNum, WsModuleCode
Close #FileNum
End Sub
You can use the above Sub as following:
Sub testSaveSheetCodeModule()
Dim strPath As String, strFileName As String, strCodeModuleName As String
strPath = ThisWorkbook.path
strFileName = "SheetCode_x.txt"
strCodeModuleName = Worksheets("Test2").codename 'use here your sheet name
SaveSoftwareFile strPath, strCodeModuleName, strFileName
End Sub
Now, the created text file contains only the code itself, without the attributes saved by exporting the code...
Import part:
"Can't enter break mode at this time" does not mean that it is an error in the code. There are some operations (allowed only if a reference to Microsoft Visual Basic for Applications Extensibility ... exists) in code module manipulation, which cannot simple be run step by step. VBA needs to keep references to its VBComponents and it looks, it is not possible when changes in this area and in this way are made.
The import code is simple and it must run without problems. You must simple run the code and test its output...

Saving extracted content from VBA in powerpoint as a new excel file

I'm new to coding, VBA and VBA in powerpoint, so this might be basic but I cant seem to get around it. I'm trying to extract some text from powerpoint files and store it separately in a new file. I found a code online that helps me output the required text onto a notepad file. However, I need it as an excel file. Every search online leads me to excel based VBA but I need to export from Powerpoint to Excel (and maybe do so basic formatting in it, like converting text to numbers or making a column bold). Following is the relevant/ exporting portion of my whole code. Please take a look and help thanks.
PS: I plan to compile the code as an Add-in for a few people with limited technical expertise, so If possible, I'd request a simple/straightforward solution or something that will work on any PC or version of powerpoint/excel. I've read making your code reference-dependant may require whoever runs the code to make references,etc before they are successfully able to run it.
Dim strFilename As String
Dim intFileNum As Integer
Dim PathSep As String
....Code that does the extraction from the Active Presentation....
On Error GoTo ErrorHandler
intFileNum = FreeFile
' PC-Centricity Alert!
' This assumes that the file has a .PPT extension and strips it off to make the text file name.
strFilename = ActivePresentation.Path _
& PathSep _
& Mid$(ActivePresentation.Name, 1, Len(ActivePresentation.Name) - 4) _
& "_Titles.TXT"
Open strFilename For Output As intFileNum
Print #intFileNum, strTitles
NormalExit:
Close intFileNum
Exit Sub
ErrorHandler:
MsgBox Err.Description
Resume NormalExit
End Sub

Vba changing directory to save

I'd like to save a file in a directory whose name changes according to the name of the Previous Month. Here is the code:
name_month = MonthName(Month(Date) - 1)
Set Newbook = Workbooks.Add
With Newbook
.Title = "TESO1"
.SaveAs Filename:="C:\Users\ee31264\Desktop\Mensile Automat\name_month \send\TESO1.xlsx"
End With
Newbook.Close
unfortunately the name_month i wrote VBA doesn't read what I mean!
That's because you need to tell Excel if what you say to it should be read as a variable or as string of text. Using "" says it is string of text and should not be evaluated.
Use this:
Filename:="C:\Users\ee31264\Desktop\Mensile Automat\" & name_month & "\send\TESO1.xlsx"
Also remember that in newer versions of Excel you also have to specify file format by using FileFormat:=51 (xlsx, use 52 for xlsm).

VBA data transfer from one workbook to another, data type mismatch error

I'm new to VBA, but learning. I've written most of the following code myself, some of it was inherited. My goal here is to loop through multiple text files (these each contain a unique set of raw data) and copy (or in some other way transfer) that data into an analysis template that I've made which will then be "saved as" with the same filename as the raw data text file. I've been working on this for several days and have done a significant amount of searching to get this far, however, I'm currently stuck with a "Run-time type '13' error - mismatch data type" that I don't understand so I don't know how to get past it. The error is # "Data.Sheets(Sheet1).Range("A1:G180000").Copy. If I comment out the aforementioned line and the one that follows it and use the line above ("Template.Sheets(Sheet1).Range("A1:G180000").Value...") I still get the same error. My code is posted below and any help is very much appreciated. Thanks :)
Sub Shift_Load_Data_Plotter_Template()
'Josh Smith
'12/27/2013
'Shift Load Data Plotter Template
'This macro will bring up the Open dialog box so you can open multiple text files and analyze them using the Shift Load Data Plotter Template
'Brings up the Open window so you can select multiple excel files to import
Dim fn As Variant, f As Integer
Dim FileName As String
'Data is the source workbook and Template is the destination workbook
Dim Data As Workbook
Dim Template As Workbook
fn = Application.GetOpenFilename("Text files,*.txt", _
1, "Select One Or More Files To Open", , True)
If TypeName(fn) = "Boolean" Then Exit Sub
'the line below was modified from from just "workbooks.open "Z:\..." to "Set Template = Workbooks.open..."
'opens the Shift Load Data Analyzer Template workbook and sets the "Template" variable equal to said workbook
Set Template = Workbooks.Open("Z:\General Reference, Tools\Shift Load Data Analyzer Template.xlsx")
For f = 1 To UBound(fn)
'the line below was modified from just "workbooks.open fn(f)" to what it shows now
'sets the "Data" variable equal to the workbook which contains the data from the text file
Set Data = Workbooks.Open(fn(f))
FileName = ActiveWorkbook.Name
'Data.Activate
'Template.Sheets(Sheet1).Range("A1:G180000").Value = Data.Sheets(Sheet1).Range("A1:G180000").Value
Data.Sheets(Sheet1).Range("A1:G180000").Copy
Template.Sheets(Sheet1).Range("A1").PasteSpecial (xlPasteValues)
'the line below used to be "ActiveWorkbook.SaveAs..."
Template.SaveAs FileName:="Z:\" & FileName & ".xlsx"
Data.Close
Next f
End Sub
The line:
Data.Sheets(Sheet1).Range("A1:G180000").Copy
Should probably read as follows:
Data.Sheets("Sheet1").Range("A1:G180000").Copy
You need quotation marks around the sheet name if you're referring to the name (the Sheets() function is looking for the sheet name you see on the tab in Excel, not the Sheet1, Sheet2, Sheet3, etc. you see in the VBA screen). Otherwise you could write it like this:
Data.Sheet1.Range("A1:G180000").Copy
Try changing it to:
Data.Sheets(1).Range("A1:G180000").Copy
Template.Sheets(1).Range("A1").PasteSpecial (xlPasteValues)

Automatically name a file based on cell data when saving a spreadsheet?

I have an .xltm template spreadsheet that I'm wondering if I can get a macro to populate the "save as" file name based on cell data, is this possible?
There are over 50 people who will have this spreadsheet, it's more of a form, and we are trying to figure out a way to keep the filenames uniform. I know there is the ThisWorkbook.BeforeSave, but I'm not really having any luck there. I just need it to make a file named something like $A$1 R $B$1 T $B$3.xlsx
Any ideas on how to do this?
Sure.
Sub SaveMyWorkbook()
Dim strPath As String
Dim strFolderPath as String
strFolderPath = "C:\"
strPath = strFolderPath & _
Sheet1.Range("A1").Value & "R" & _
Sheet1.Range("B1").Value & "T" & _
Sheet1.Range("B3").Value & ".xlsx"
ActiveWorkbook.SaveAs Filename:=strPath
End Sub
EDIT: After you clarified your question in your comment below, I can now safely say that the answer is: No, what you are asking is not possible.
What is possible is to put a big, fat command button on your sheet that says "Press me to save", and have that button call the above Sub. You can set a fixed folder, as in the example above, or have the user pick a folder using the FileDialog object (or the GetSaveAsFilename function, but then the user will be able to change the suggested filename, so less safe).

Resources