I would like to carry out the captioned task with the following codes modified from extendoffice.com (thank you).
Sub export_data_to_CSV()
Dim Rng As Range
Dim WorkRng As Range
Dim xFile As Variant
Dim xFileString As String
Dim LR As Long
LR = Application.WorksheetFunction.CountA(Worksheets("MAIN").Range("A1:A50001"))
Set WorkRng = Application.Selection
Set WorkRng = Worksheets("MAIN").Range("A2:J" & LR)
Application.ActiveSheet.Copy
Application.ActiveSheet.Cells.Clear
WorkRng.Copy Application.ActiveSheet.Range("A1")
Set xFile = CreateObject("Scripting.FileSystemObject")
xFileString = Application.GetSaveAsFilename("", filefilter:="Comma Separated Text (*.CSV), *.CSV")
Application.ActiveWorkbook.SaveAs Filename:=xFileString, FileFormat:=xlCSV, CreateBackup:=False
End Sub
The code works fine, however, it saves all formulas and even my button to the target file. What should I do to the code if I only want to save values to the target CSV file?
CSV files can't have formulas or buttons by definition. I think you're just seeing them in the currently open Excel instance, but if you were to open the newly saved CSV file, they would not be present.
To address your follow-up question:
If I want to close the target file instantly with the code, what lines should I add?
ActiveWorkbook.Close SaveChanges:=False
Here is some demo code. It:
copies Sheet1 to a new workbook
clears all formula cells in the clone (copied) worksheet
saves the clone as .csv
closes the clone workbook
Sub KopyKat()
'
Sheets("Sheet1").Select 'move to sheet
Sheets("Sheet1").Copy 'copy sheet to new workbook
ActiveSheet.Cells.SpecialCells(-4123).Clear 'get rid of formulas
'then save as .csv
ActiveWorkbook.SaveAs Filename:="C:\Users\garys\Desktop\bk.csv", FileFormat _
:=xlCSVUTF8, CreateBackup:=False
ActiveWorkbook.Close 'close the new workbook
' the original workbook is now active again
End Sub
Related
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
I need help on trying to copy a range of data from excel to a new .txt file
I have gotten to the point of creating a text file but i am stuck in trying to copy the range and pasting it to the .txt file.
The format of the data needs to be vertical to enable another program to read it.
Try this
Option Explicit
'Copy the contents of a worksheet, and save it as a new workbook as a .txt file
Sub Sheet1_Tab()
Dim wbSource As Workbook
Dim wsSource As Worksheet
Dim wbDest As Workbook
Dim fName As String
'References
Set wbSource = ActiveWorkbook
Set wsSource = ThisWorkbook.Sheets("Sheet1") 'Change as per your requirement
Set wbDest = Workbooks.Add
'Copy range on original sheet
'Assuming your range is contiguous.
wsSource.UsedRange.Copy
'Save in new workbook
wbDest.Worksheets(1).Cells(1, 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
Application.CutCopyMode = False
'Get file name and location
fName = ThisWorkbook.Path & "\Sheet1.txt"
'Save new tab delimited file
wbDest.SaveAs fName, xlText
wbDest.Close SaveChanges:=True
End Sub
You can also use notepad route :
Alternately The following program gets values from a range of cells on a worksheet to copy to clipboard, gets the clipboard content into a string, saves that string to a temp file and then opens Notepad.exe with the content of the temp file
Code:
Option Explicit
Sub ThroughNotePadTxt()
Dim rngDat As Range
Dim strData As String
Dim strTempFl As String
' copy some range values
Set rngDat = Sheets("Sheet1").Range("A1:G20")' Change as per your requirement
rngDat.Copy
' get the clipboard data
' magic code for is for early binding to MSForms.DataObject
With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
.GetFromClipBoard
strData = .GetText
End With
' write to temp file
strTempFl = "C:\temp.txt" 'Change as per your reqirement. Directory to have permission to write the file
With CreateObject("Scripting.FileSystemObject")
' true to overwrite existing temp file
.CreateTextFile(strTempFl, True).Write strData
End With
' open notepad with tempfile
Shell "cmd /c ""notepad.exe """ & strTempFl & """", vbHide
End Sub
(Beginner VBA coder here!)
Does anyone know how to extract multiple, specific cell data from multiple closed workbooks that have the same worksheet format?
I am currently tasked to copy very specific data from certain cells from many different and new (but same format) sources and transfer them into another group of specific cells in an existing masterlist with different worksheets.
This is the code I wished would help, but it is lacking in too many ways as compared to what I need...
Sub Importsheet()
Dim Importsheet As Worksheet
'import worksheet from a closed workbook
Sheets.Add Type:= _
'e.g. directory below
"C:\Users\Loli\Desktop\Testing1.xlsx"
End Sub
This code helps me get the sheets out of the closed source workbook but not the specifically placed cells in the closed source excel. It also can't paste the data in specifically placed cells in different sheets in the destination excel.
It is very difficult to completely understand your requirements as it seems like sometimes you want to copy a range and some other times a single cell, so to point you in the right direction my answer only shows how to open and copy the relevant Sheet into your master workbook to then be able to reference the cell/ranges you want
(I would once you get your data then delete the Worksheet, so that your master doesn't suddenly becomes massive in size):
Sub ImportSheet()
Dim sImportFile As String, sFile As String
Dim sThisBk As Workbook
Dim vfilename As Variant
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set sThisBk = ActiveWorkbook
sImportFile = Application.GetOpenFilename( _
FileFilter:="Microsoft Excel Workbooks, *.xls; *.xlsx", Title:="Open Workbook") 'open dialog to choose the file you want, you can change this to loop through a folder if they are all in there.
If sImportFile = "False" Then 'check if a file was selected before importing
MsgBox "No File Selected!"
Exit Sub
Else
vfilename = Split(sImportFile, "\")
sFile = vfilename(UBound(vfilename))
Application.Workbooks.Open Filename:=sImportFile 'open the selected file
Set wbBk = Workbooks(sFile)
With wbBk
If SheetExists("Raw_Data") Then ' you should change this to the date, you can do this easily by using a variable such as if SheetExists(variableDate) then, where variableDate = "12/12/2017" or something similar
Set wsSht = .Sheets("Raw_Data")
wsSht.Copy before:=sThisBk.Sheets("Sheet1") 'copy the worksheet into your master
'WsSht.range("A1:B2").copy Destination:=sThisBk.Sheets("Temp").Range("A1").paste xlpastevalues 'use this to copy a specified range in this case A1:B2 to a sheet in master workbook called Temp A1
Else
MsgBox "There is no sheet with name :Raw_Data in:" & vbCr & .Name
End If
wbBk.Close SaveChanges:=False
End With
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Function SheetExists(sWSName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = Worksheets(sWSName)
If Not ws Is Nothing Then SheetExists = True
End Function
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.
Related: Save each sheet in a workbook to separate CSV files
I’ve inherited some code that I’m trying to update. The intention is to take a particular range from each of certain (macro-generated) sheets and save them as distinct CSV files. Here’s the existing code, somewhat simplified & with error checking removed:
' Save sheets not named "Table" as CSV files
Sub Extract_CSV()
Dim CurrentSheet As Integer
For CurrentSheet = 1 To ActiveWorkbook.Worksheets.Count
ActiveWorkbook.Worksheets(CurrentSheet).Activate
With ActiveWorkbook.Worksheets(CurrentSheet)
If (.Name <> "Table") Then
.Range("J3:J322").Select
.SaveAs Filename:=ActiveSheet.Name, FileFormat:=xlCSV, CreateBackup:=True
End If
End With
Next CurrentSheet
End Sub
The line .Range("J3:J322").Select is a noop in this context, but how can I achieve what this was trying to do: save only the range J3:J322 to this new CSV file?
I've augmented your code and added comments. This code creates a temporary workbook to copy/paste your selection and save it. The temporary workbook is then closed. Note that this code will overwrite existing files without prompts. If you wish to see prompts, then remove the Application.DisplayAlerts lines before and after the loop.
Sub Extract_CSV()
Dim wb As Workbook
Dim CurrentSheet As Integer
For CurrentSheet = 1 To ActiveWorkbook.Worksheets.Count
ActiveWorkbook.Worksheets(CurrentSheet).Activate
'Suppress Alerts so the user isn't prompted to Save or Replace the file
Application.DisplayAlerts = False
With ActiveWorkbook.Worksheets(CurrentSheet)
If (.Name <> "Table") Then
'Select the range and copy it to the clipboard
.Range("J3:J322").Select
Selection.Copy
'Create a temporary workbook and paste the selection into it
Set wb = Application.Workbooks.Add
wb.Worksheets(1).Paste
'Save the temporary workbook with the name of the the sheet as a CSV
wb.SaveAs Filename:=ActiveSheet.Name, FileFormat:=xlCSV, CreateBackup:=True
'Close the workbook
wb.Close
End If
End With
'Restore alerts
Application.DisplayAlerts = True
Next CurrentSheet
End Sub
You may copy the target range, paste it in a new worksheet (you may need to paste as values, and paste number format as well), and then save that worksheet.
The code below embodies the idea. Lines commented with '* are added/modified as compared to your code. A few things to bear in mind:
By pasting values, you prevent the (unlikely) case of having cells with functions whose evaluated value changes upon pasting in the newly created workbook.
Using rng instead of selecting the Range is the recommended practice. If you do not have a lot of these operations, you would likely not notice the (minor) time saving.
Disabling DisplayAlerts eliminates alerts during macro execution (please see this to find out if you would like to make adjustments).
' Save sheets not named "Table" as CSV files
Sub Extract_CSV()
Dim CurrentSheet As Integer
For CurrentSheet = 1 To ActiveWorkbook.Worksheets.Count
ActiveWorkbook.Worksheets(CurrentSheet).Activate
Application.DisplayAlerts = False '*
With ActiveWorkbook.Worksheets(CurrentSheet)
If (.Name <> "Table") Then
'.Range("J3:J322").Select
Dim rng As Range '*
Set rng = .Range("J3:J322") '*
rng.Copy '*
Dim wb As Workbook '*
Set wb = Application.Workbooks.Add '*
wb.Worksheets(1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False '*
wb.SaveAs Filename:=ActiveSheet.Name, FileFormat:=xlCSV, CreateBackup:=True '*
wb.Close '*
End If
End With
Application.DisplayAlerts = True '*
Next CurrentSheet
End Sub