adding a sub folder using activeworkbook.path syntax - excel

ok so this is a short peace in a big workbook... All i am trying to do is tell it a certain place to save.
ActiveWorkbook.SaveCopyAs _
FileName:=ActiveWorkbook.Path "\OLD " & Range("D1").Value & ".XLSM"
This does exactly as it is supposed to however, i want to say basically
"activeworkbook.path" plus give it one further step and designate a folder called "old" that it will go to.
in essence it would look like this
\documents\test\my-file.xlsm
to this
\documents\test\OLD\my-file.xlsm
any hints?

You have a space in "\OLD ", and you are not closing off \OLD to be a folder.
The line should look like
ActiveWorkbook.SaveCopyAs _
FileName:=ActiveWorkbook.Path & "\OLD\" & Range("D1").Value & ".XLSM"
I would also strongly consider qualifying your Range("D1") with your worksheet.
Dim fileNameRng as range
Set fileNameRng = thisworkbook.worksheets("Sheet1").Range("D1")
ActiveWorkbook.SaveCopyAs _
FileName:=ActiveWorkbook.Path & "\OLD\" & fileNameRng.Value & ".XLSM"

Related

ActiveWorkbook.SaveAs not being able to run

This is probably a really simple task, but for some reason my code doesnt run. This code has worked for the past few months but when I initiate the command now it doesnt work.
The code that I had used (without any change) is the following:
Sub Copy()
ActiveWorkbook.SaveAs "C:\Users\[File Location]" & "File Name " & Format(Now(), "DD-MMM-YYYY") & ".xlsm", FileFormat:=52
End Sub
Wondering if anyone could provide any advice / tips on how to solve/troubleshoot >.< many thanks in advance.
Here it is broken up a little for you. The Environ() function just gets the user name of whoever is logged in when the code runs.
Replace how File1 is created if you want something else. (you did not include that part in your question)
Sub SaveIt()
Dim SavePath As String
Dim File1 As String
Dim Filename As String
SavePath = "C:\Users\" & Environ("UserName") & "\Desktop\TRD\Run\"
File1 = Split(ActiveWorkbook.Name, ".")(0) ' strip out the file extension
Filename = File1 & " " & Format(Now(), "DD-MMM-YYYY") & ".xlsm"
ActiveWorkbook.SaveAs SavePath & Filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
Note: This assumes the folder you are saving it to exists already.

Variable Workbook Name in Formula

I am trying to write a code that takes a variable workbook name (declared earlier) and inputs it into a formula that will be pasted into a cell.
I have it to the point where the formula works if I just write the workbook in, and I have the variable declaration with the workbook path working okay, I just can't figure out the formatting to drop the variable into the formula code.
'''Spreadsheet opening and variable declaration
strFileToOpen = Application.GetOpenFilename _
(Title:="Select an updated Inventory Report", _
FileFilter:="Excel Files *.xls* (*.xls*),")
If strFileToOpen = False Then
'Displaying a message if file not choosedn in the above step
MsgBox "No file selected.", vbExclamation, "Sorry!"
'And existing from the procedure
Exit Sub
Else
End If
Workbooks.Open Filename:=strFileToOpen
Set InvRpt = ActiveWorkbook
InvRptName = ActiveWorkbook.FullName
Set InvSht = InvRpt.Worksheets("ALL")
'''Formula insert
ActiveCell.Formula = "=IF(ISERROR(GETPIVOTDATA(""Sec QTY Sum"", 'InvRptName'!$A$4,""Alias"",""" & y & """)),0,GETPIVOTDATA(""Sec QTY Sum"", 'InvRptName'!$A$4,""Alias"",""" & y & """))"
The end result would be for this code to work exactly like this, but with a variable instead of the workbook/sheet name:
ActiveCell.Formula = "=IF(ISERROR(GETPIVOTDATA(""Sec QTY Sum"", '[8-14-19 AM INVENTORY.xls]Sheet2'!$A$4,""Alias"",""" & y & """)),0,GETPIVOTDATA(""Sec QTY Sum"", '[8-14-19 AM INVENTORY.xls]Sheet2'!$A$4,""Alias"",""" & y & """))"
It always helps to place a Break Point into the line where you are having issues then use the Intermediate Window to figure out where it is going wrong. For example;
Place a Break Point at the last line where you have ActiveCell.Formula =
Run the code
In the Intermediate Window type ?"=IF(ISERROR(GETPIVOTDATA(""Sec QTY Sum"", 'InvRptName'!$A$4,""Alias"",""" & y & """)),0,GETPIVOTDATA(""Sec QTY Sum"", 'InvRptName'!$A$4,""Alias"",""" & y & """))"
Note; The ? instructs the Intermediate Window that you want to see a return value.
If it compiles ok you should see a resulting string, see if it looks as you expected. I'd guess your result will include the text 'InvRptName' where you are expecting '[8-14-19 AM INVENTORY.xls]Sheet2'.
To get '[8-14-19 AM INVENTORY.xls]Sheet2'!$A$4 try using;
?"'[" & ActiveWorkbook.Name & "]" & ActiveSheet.Name & "'!$A$4"
Another couple hot tips;
Use Debug.Print "add your messages here or a variable " & InvRptName within your code to output debug messages.
Use the Intermediate Widow to fix variables during execution InvRptName = "'[" & ActiveWorkbook.Name & "]" & ActiveSheet.Name & "'!$A$4" notice I excluded the ? this time.

Subscript out of range error - saveas method

Trying to get Excel to "saveas" a workbook by using the following code:
Sub SaveWorkbook(my_FileName, sFolder)
Dim workbook_Name As String
Dim fName As String
fName = CStr(Range("B9").Value)
workbook_Name = "\" & fName & ".xls"
Workbooks(my_FileName).SaveAs fileName:=sFolder & workbook_Name
End Sub
my_FileName and sFolder are being passed by another function:
Sub ProduceDoc()
MsgBox "Please Select the File that Contains the Document"
my_FileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*,*.xsl*,*.xm*")
sFolder = "C:\Users\" & InputBox("Please type your employee id") & "\Desktop\" & InputBox("What will you name your folder?")
Workbooks.Open (my_FileName)
SaveWorkbook (my_FileName)
End Sub
The subscript error is currently being thrown for the line:
Workbooks(my_FileName).SaveAs fileName:=sFolder & workbook_Name
and I can't figure out why. I'm assuming it's happening because I'm forgetting something simple.
What I've done so far to test:
Verified that my_FileName is successfully being passed to the function SaveWorkbook(), and it is. I was able to open the document specified in function ProduceDoc() and get my_FileName to print in a certain cell within SaveWorkbook()
That's all I have in the toolkit atm. Any thoughts?
Edit: I've now updated the line Workbooks(my_FileName).SaveAs fileName:=sFolder & workbook_Name to show new state, and also sFolder is being called in . It is still giving the same error.
I figured it out.
Everything was formatted correctly in all variables, except for these two lines:
workbook_Name = "\" & fName & ".xls"
Workbooks(my_FileName).SaveAs fileName:=sFolder & workbook_Name
Excel didn't like a few things here, so I tried to make it as basic as I could. I combined the concatenation of sFolder and workbook_Name into one variable, removed ".xls", and added the fileFormat:=xlWorkbookNormal argument into the SaveAs method.
What I think really fixed this is how I called the SaveAs method. Changed that to "ActiveWorkbook" rather than what is was previously.
workbook_Name = sFolder & "\" & fName
ActiveWorkbook.SaveAs fileName:=workbook_Name, fileFormat:=xlWorkbookNormal
It all behaves as expected now!
hope this helps anyone who runs into this in the future!

VBA Export and save to CSV issues

Found the below code online, though it's a bit strange when I run the macro for dates as my dates will convert from:
[DD/MM/YYYY] to [MM/DD/YYYY]
example:
31/07/2017 to 07/31/2017.
anyone able to assist, I would want to keep it was [DD/MM/YYYY].
Refer to below:
Dim strName As String
Dim filepath As String
Application.ScreenUpdating = False
strName = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name & " " & ActiveSheet.Name & ".csv"
ActiveSheet.Copy 'copy the sheet as a new workbook
ActiveWorkbook.SaveAs Filename:=strName, FileFormat:=xlCSV
ActiveWorkbook.Close SaveChanges:=False
Application.ScreenUpdating = True
MsgBox "File has been Created and Saved as: " & vbCr & strName, , "Copy & Save Report"
thanks,
Depending on your local language settings (specified in Control Panel), the following should work:
ActiveWorkbook.SaveAs Filename:=strName, FileFormat:=xlCSV, Local:=True
This should ideally be used by specifying the TextCodepage parameter of the SaveAs method.
However, according to MSDN reference, this parameter is ignored for all languages of Excel.
A previous question on SO addresses this, and suggests instead using FileFormat:=xlUnicodeText, and then setting the extension to .csv, i.e.:
ActiveWorkbook.SaveAs Filename:=strName & ".csv", FileFormat:=xlUnicodeText
However, this does not seem to work for my part when testing your scenario.

VBA Save As resulting undefined file type

I have a simple VBA that runs the same report several times while cycling through different names, saving each report as a seperate workbook.
Everything works fine, but 1 of the reports is always saved as an 'undefined' file type, and I have to manual change it to excel afterwards. All others save fine, so I can't figure out the issue. I've tried playing with the SaveAs FileFormat, but none of them have solved this.
For Each c In MCH
Detail.Range("B8:E10000").ClearContents
Data.Rows("4:4").AutoFilter Field:=2, Criteria1:= _
c.Value
lr = Data.Cells(Rows.Count, "E").End(xlUp).Row
Data.Range("E5:H" & lr).Copy Detail.Range("B8")
Sheets("Detail").Calculate
Set name = Detail.Range("B4")
Sheets("Detail").Copy
ActiveSheet.Cells.Copy
ActiveSheet.Range("A1").PasteSpecial Paste:=xlValues
ActiveSheet.Range("A1").Select
Set wb = ActiveWorkbook
wb.SaveAs ThisWorkbook.Path & "\" & name
wb.Close False
Next
You didn't select the file format.
Instead of:
Set wb = ActiveWorkbook
wb.SaveAs ThisWorkbook.Path & "\" & name
Try this:
Xslx
ActiveWorkbook.SaveAs Filename:= ThisWorkbook.Path & "\" & name, FileFormat:= xlOpenXMLWorkbook, CreateBackup:=False
Text file (txt)
ActiveWorkbook.SaveAs Filename:= ThisWorkbook.Path & "\" & name, FileFormat:= xlUnicodeText, CreateBackup:=False
For other FileFormats see this enumeration:
https://msdn.microsoft.com/en-us/library/bb241279(v=office.12).aspx
In case of issues
In case you are experiencing issues with the above do the following:
Go to the Developer Tab
Click on Record Macro
Save the file manually in the desired format
Click on Stop Recording
Open your VBA Project and get the generated code

Resources