VBA how do i open another workbook? - excel

I am trying to open another workbook, using the code below
Sheets("Range").Activate
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Workbooks.Open ("AvgStdev.xlsm")
And it was working before, but now excel is prompting the file cant be found. Help please :/

You can do what you want easily if you declare your variable as discussed HERE.
So if we are to apply it, you can open your workbook like this:
Dim wb As Workbook
Dim myfilename As String
myfilename = "C:\Users\Ayaz\Desktop\Analysis\AvgStdev.xlsm"
'~~> open the workbook and pass it to workbook object variable
Set wb = Workbooks.Open(myfilename)
'~~> More codes here
Now later in your code if you are saving the same file:
wb.Save '~~> save
wb.Close '~~> close
Or you can do it using Close method only:
wb.Close True '~~> explicit SaveChanges argument to true
Now if however you like to save it as another file:
Dim newfilename As String
newfilename = "C:\Users\Ayaz\Desktop\Analysis\Another.xlsm"
'~~> If you are saving it in a format other than .xlsx,
'~~> you have to be explicit in the FileFormat argument
wb.SaveAs newfilename, xlOpenXMLWorkbookMacroEnabled
wb.Close
HTH.

Right click on your excel file and obtain the filepath from the properties, then substitute the actual filepath into the below:
Workbooks.Open ("filepath\AvgStdev.xlsm")

Related

Convert .xlsm to .csv [duplicate]

I appreciate there are lots of entries like save individual excel sheets as csv
and Export each sheet to a separate csv file - But I want to save a single worksheet in a workbook.
My code in my xlsm file has a params and data sheet. I create a worksheet copy of the data with pasted values and then want to save it as csv. Currently my whole workbook changes name and becomes a csv.
How do I "save as csv" a single sheet in an Excel workbook?
Is there a Worksheet.SaveAs or do I have to move my data sheet to another workbook and save it that way?
CODE SAMPLE
' [Sample so some DIMs and parameters passed in left out]
Dim s1 as Worksheet
Dim s2 as Worksheet
Set s1 = ThisWorkbook.Sheets(strSourceSheet)
' copy across
s1.Range(s1.Cells(1, 1), s1.Cells(lastrow, lastcol)).Copy
' Create new empty worksheet for holding values
Set s2 = Worksheets.Add
s2.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
' save sheet
s2.Activate
strFullname = strPath & strFilename
' >>> BIT THAT NEEDS FIXIN'
s2.SaveAs Filename:=strFullname, _
FileFormat:=xlCSV, CreateBackup:=True
' Can I do Worksheets.SaveAs?
Using Windows 10 and Office 365
This code works fine for me.
Sub test()
Application.DisplayAlerts = False
ThisWorkbook.Sheets(strSourceSheet).Copy
ActiveWorkbook.SaveAs Filename:=strFullname, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
It's making a copy of the entire strSourceSheet sheet, which opens a new workbook, which we can then save as a .csv file, then it closes the newly saved .csv file, not messing up file name on your original file.
This is fairly generic
Sub WriteCSVs()
Dim mySheet As Worksheet
Dim myPath As String
'Application.DisplayAlerts = False
For Each mySheet In ActiveWorkbook.Worksheets
myPath = "\\myserver\myfolder\"
ActiveWorkbook.Sheets(mySheet.Index).Copy
ActiveWorkbook.SaveAs Filename:=myPath & mySheet.Name, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Next mySheet
'Application.DisplayAlerts = True
End Sub
You just need to save the workbook as a CSV file.
Excel will pop up a dialog warning that you are saving to a single sheet, but you can suppress the warning with Application.DisplayAlerts = False.
Don't forget to put it back to true though.
Coming to this question several years later, I have found a method that works much better for myself. This is because the worksheet(s) I'm trying to save are large and full of calculations, and they take an inconvenient amount of time to copy to a new sheet.
In order to speed up the process, it saves the current worksheet and then simply reopens it, closing the unwanted .csv window:
Sub SaveThisSheetInParticular()
Dim path As String
path = ThisWorkbook.FullName
Application.DisplayAlerts = False
Worksheets("<Sheet Name>").SaveAs Filename:=ThisWorkbook.path & "\<File Name>", FileFormat:=xlCSV
Application.Workbooks.Open (path)
Application.DisplayAlerts = True
Workbooks("<File Name>.csv").Close
End Sub
Here the Sheet and csv filename are hardcoded, since nobody but the macro creator (me) should be messing with them. However, it could just as easily be changed to store and use the Active Sheet name in order to export the current sheet whenever the macro is called.
Note that you can do this with multiple sheets, you simply have to use the last filename in the close statement:
Worksheets("<Sheet 1>").SaveAs Filename:=ThisWorkbook.path & "\<File 1>", FileFormat:=xlCSV
Worksheets("<Sheet 2>").SaveAs Filename:=ThisWorkbook.path & "\<File 2>", FileFormat:=xlCSV
[...]
Workbooks("<File 2>.csv").Close

save and close a workbook with its existing name and reopen it with VBA

I have my VBA code below, I would like that my macro saves and closes on mydesktop my activework with its existing name, then I would like that my macro reopens it. When I execute my macro, it saves and closes my activeworkbook with its existing name on my desktop but it does not reopen the excel file. It seems that the part of the code Workbooks.Open ("\\C:\users\ing\users3\Xavi\Desktop\" & ActiveWorkbook.Name) does not work in my macro.
If someone know the solution, that would be great.
Many thanks
Xavi
Sub openandsaveactiveworkbookandreopenit ()
Dim myactiveworkbook As Workbook
Set myactiveworkbook = ActiveWorkbook
ActiveWorkbook.SaveAs FileName:="\\xxxyyyy\users\ing\users3\Xavi\Desktop\" & ActiveWorkbook.Name _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWorkbook.Close
Workbooks.Open ("\\xxxyyyy\users\ing\users3\Xavi\Desktop\" & ActiveWorkbook.Name)
End Sub
You can't run this macro from the ActiveWorkbook -- it needs to run from a different workbook. See #FoxfireAndBurnsAndBurns comment.
You've declared (good practice) myactiveworkbook but you never use it!
Once you've closed ActiveWorkbook, you can no longer access it's Name property because it doesn't exist. Save that property in a string variable.
Try this variation, with the macro in a workbook that is not the Active Workbook. It works OK here.
Option Explicit
Sub openandsaveactiveworkbookandreopenit()
Dim myactiveworkbook As Workbook
Dim myactiveworkbookname As String
Set myactiveworkbook = ActiveWorkbook
myactiveworkbook.SaveAs Filename:="c:\users\ron\desktop\" & ActiveWorkbook.Name _
, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
myactiveworkbookname = myactiveworkbook.Name
myactiveworkbook.Close
Workbooks.Open ("c:\users\ron\Desktop\" & myactiveworkbookname)
End Sub

Save sheet as values in external file

I have a workbook with 6 sheets.
I want to save the values (not formulas) of the sheets 1 and 2 in 2 external files.
Tried this:
Worksheets("Sheet1").Copy
With ActiveWorkbook
.SaveAs Filename:="D:\sheet1.xls", FileFormat:=56, CreateBackup:=False
End With
Worksheets("Sheet2").Copy
With ActiveWorkbook
.SaveAs Filename:="D:\sheet2.xls", FileFormat:=56, CreateBackup:=False
End With
It Works. But:
It's saving the formulas, not its values.
If file exists, prompt a message asking if want to override
You would need to convert the formulas into values on your own. Do something like the following:
ThisWorkbook.Worksheets("Sheet1").Copy 'create a copy in a new workbook
Dim wb As Workbook
Set wb = ActiveWorkbook 'get the new workbook
'change formulas into values
wb.Worksheets(1).UsedRange.Value = wb.Worksheets(1).UsedRange.Value
'save
wb.SaveAs Filename:="D:\sheet1.xls", FileFormat:=56, CreateBackup:=False
'close it
wb.Close SaveChanges:=False
If you want to get rid of the overwriting question, check if the file D:\sheet1.xls alrady exists and kill it before you save it. I don't explain that in detail because there are already one million tutorials for that.
Improvement
Use a procedure to re-use your code:
Public Sub ExportWorksheet(ByVal SheetName As String, ByVal ExportToFile As String)
ThisWorkbook.Worksheets(SheetName).Copy
Dim wb As Workbook
Set wb = ActiveWorkbook
wb.Worksheets(1).UsedRange.Value = wb.Worksheets(1).UsedRange.Value
If Dir(ExportToFile) <> vbNullString Then Kill ExportToFile
wb.SaveAs Filename:=ExportToFile, FileFormat:=56, CreateBackup:=False
wb.Close SaveChanges:=False
End Sub
Sub TestIt()
ExportWorksheet SheetName:="Sheet1" ExportToFile:="D:\sheet1.xls"
ExportWorksheet SheetName:="Sheet2" ExportToFile:="D:\sheet2.xls"
End Sub
Note whenever you feel you would have to copy a code, split it apart into a seperate procedure to avoid redundancy.
A small example which may help: Option Explicit
Sub test()
Dim wsSou As Worksheet, wsDes As Worksheet
With ThisWorkbook
Set wsSou = .Worksheets("Sheet1")
Set wsDes = .Worksheets("Sheet2")
'Copy Paste - ONLY Values
wsSou.UsedRange.Copy
wsDes.Range("A1").PasteSpecial xlPasteValues
'Copy Paste - Values and Formattings
wsSou.UsedRange.Copy wsDes.Range("A1")
End With
End Sub

Copy excel range to new xlsx file

I am trying to use the below code to copy a range from a macro enabled workbook to a new excel file that then gets sent on to a company.
The code worked when saving the new file as a csv but I noticed it lost the formatting so I need to save it as an excel file.
I get a runtime error 1004 and message to say method save as of object workbook failed.
The only change I made was taking the .csv extension and changing to .xlsx.
Sub exportJuneCredit()
'
' export Macro
Range("A1:H500").Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
ActiveWorkbook.SaveAs Filename:= _
"file path Credits.xlsx" _
, FileFormat:=xlsx, CreateBackup:=False
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
Try this: -
Sub exportJuneCredit()
Dim WkSht_Src As Worksheet
Dim WkBk_Dest As Workbook
Dim WkSht_Dest As Worksheet
Dim Rng As Range
Set WkSht_Src = ActiveSheet
Set Rng = WkSht_Src.Range("A1:H500")
Set WkBk_Dest = Application.Workbooks.Add
Set WkSht_Dest = WkBk_Dest.Worksheets(1)
Rng.Copy WkSht_Dest.Range("A1")
Set WkSht_Dest = Nothing
WkBk_Dest.SaveAs Filename:="file path Credits.xlsx", FileFormat:=XlFileFormat.xlWorkbookNormal, CreateBackup:=False
WkBk_Dest.Close 0
Set WkBk_Dest = Nothing
Set Rng = Nothing
Set WkSht_Src = Nothing
End Sub
The issue I believe you were having was that activeworkbook may not have been the workbook you wanted to save, to get around this I have explicitly declared items.
I also change the copy/paste to use just the copy feature.
Although would not let me open file after it was created. Changed the file format to: xlOpenXMLWorkbook as mentioned by YowE3K. – PA060 Jun 12 '17 at 11:42
The code given by Gary Evans is to save as the backward compatible .xls format. If you change the filename to have .xls as extension it will allow you to open.
If you want .xlsx file, then change file format to xlOpenXMLWorkbook as mentioned by YowE3K.

Why does VBA ActiveWorkbook.SaveAs change the open spreadsheet?

My function is as follows:
Sub saveCSV()
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:= _
"c:\temp\file.csv", FileFormat:=xlCSV _
, CreateBackup:=False
End Sub
I'm trying to export the active worksheet to CSV. When I run the code in the title, Book1.xlsm changes to file.csv and Sheet1 changes to file. The export works fine. How can I do the export without these unwanted side effects?
That's always how SaveAs has worked. The only way to get around this is to copy the worksheet and do a SaveAs on the copy, then close it.
EDIT: I should add an example as it's not that difficult to do. Here's a quick example that copies the ActiveSheet to a new workbook.
Dim wbk As Workbook
Set wbk = Workbooks.Add
ActiveSheet.Copy wbk.Sheets(1) ' Copy activesheet before the first sheet of wbk
wbk.SaveAs ....
wbk.Close
A complicated workbook may get issues with links and macros, but in ordinary scenarios this is safe.
EDIT 2: I'm aware of what you're trying to do, as your other question was about trying to trigger an export on every change to the sheet. This copy sheet approach presented here is likely to be highly disruptive.
My suggestion is to write a CSV file by hand to minimise GUI interruption. The sheet is likely to become unusable if the saves are occurring at high frequency. I wouldn't lay the blame for this at the door of Excel, it simply wasn't built for rapid saves done behind the scenes.
Here's a little routine that does what you want by operating on a copy of the original ... copy made via file scripting object. Hardcoded to operate on "ThisWorkbook" as opposed to active workbook & presumes ".xlsm" suffix - could tweak this to do the job I think:
Public Sub SaveCopyAsCsv()
Dim sThisFile As String: sThisFile = ThisWorkbook.FullName
Dim sCsvFile As String: sTempFile = Replace(sThisFile, ".xlsm", "_TEMP.xlsm")
ThisWorkbook.Save ' save the current workbook
' copy the saved workbook ABC.xlsm to TEMP_ABC.xlsm
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Call fso.deletefile(sTempFile, True) ' deletes prev temp file if it exists
On Error GoTo 0
Call fso.CopyFile(sThisFile, sTempFile, True)
' open the temp file & save as CSV
Dim wbTemp As Workbook
Set wbTemp = Workbooks.Open(sTempFile) ' open the temp file in excel
' your prev code to save as CSV
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:="c:\temp\file.csv", FileFormat:=xlCSV, CreateBackup:=False
wbTemp.Close ' close the temp file now that the copy has been made
Application.DisplayAlerts = True
' delete the temp file (if you want)
On Error Resume Next
Call fso.deletefile(sTempFile, True) ' deletes the temp file
On Error GoTo 0
End Sub

Resources