Copying the range and pasting it directly to a .txt file - excel

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

Related

VBA to export data to CSV file (only values)

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

Issues to copy and paste from a workbook (loop error)

I'm trying to loop through a folder of excel files (around 6 files or so), copy data from a named table and paste values into a master. I've tried using the DataBodyRange instead of standard range but i'm having problems with it pasting into ThisWorkbook (where the master will live). The paste destination is the same size as source and should be pasted on next empty row,so on and so forth. I'm two days into banging my head on the wall and can't figure this out.Any help or insight would be amazing.
Sub SalesTrackerCompiler()
Dim Myfile As String, str As String, mydir As String, wb As Workbook
Set wb = ThisWorkbook
mydir = "C:\Users\$$$$$$$$$$$$\"
Myfile = Dir(mydir & "*.xlsm")
ChDir mydir
Application.ScreenUpdating = 0
Dim erow As Long
Do While Myfile <> ""
Workbooks.Open (Myfile)
With Worksheets("Data Input Table")
Worksheets("data input table").ListObjects("DataInputSource").AutoFilter.ShowAllData
Set rng = ListObjects.Item(1).DataBodyRange.Select
rng.Copy wb.Worksheets("regional source data").Cells(Rows.Count, "a").End(xlUp).Offset(1, 0)
ActiveWorkbook.Close True
End With
Myfile = Dir()
Loop
End Sub
Add a break point to the line where you know the error is, run your code, when it stops use the immediate window and type ?ListObjects(1).Name press enter and see if you get the same error, I suggest you will.
You need to reference the specific Workbook and Worksheet to to get the ListObject. Try changing
Workbooks.Open (Myfile)
to
set new_workbook = Workbooks.Open(Myfile)
then use (assuming the ListObject is in Worksheet 1)
Set rng = new_workbook.Worksheets(1).ListObjects(1).DataBodyRange

VBA: copy range of data across workbooks and "save as" function in loop

I want to copy a range of cells in my .csv file into a template.csv (named "pp"). Then I would like to save the template as "name of the original .csv file_2", without closing the original template as I would need it to do this procedure in loop for all the files in my folder. I have come up with this code that doesn't work:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim pp As Workbook ' Workbook to receive the copied data
Dim ppSht As Worksheet ' Worksheet where copied data will be inserted
Dim Wkb As Workbook ' Temporary workbook for the Loop
Dim Sht As Worksheet ' Temporary worksheet variable for the loop
MyFile = Dir("R:\COMT study\Silvia\Cognitive data\COMT 1\Tasks\CPT*.csv*")
Set pp = Workbooks("pp.csv")
Set ppSht = pp.Sheets("Sheet1")
Do While MyFile <> ""
Set Wkb = Workbook.Open("R:\COMT study\Silvia\Cognitive data\COMT 1\Tasks\CPT" & MyFile)
Set Sht = Wkb.Worksheets("sheet1")
Sht.Range("A1:G113").Copy
With ppSht
.Range("A1:G113").PasteSpecial xlPasteFormulas
End With
pp.SaveCopyAs Filename = MyFile_2.csv
Wkb.Close True
MyFile = Dir
Loop
End Sub
I am new to the vba coding and I am not sure what I am doing wrong as I don't get any error messages, the code simply doesn't run. Do you have any suggestion?
First of all I would like to recommend you how to use a CSV file (Comma-separated values). By this a csv file does not have any sheets. Therefore you can reach the worksheet with the following, there wb is the workbook. Another good advice is to use Option Explicit that enables some error codes, example if you get to initialize a variable.
Dim pp As Workbook
pp.Worksheets (1)
Do While MyFile <> ""
Set wb = Workbooks.Open("R:\COMT study\Silvia\Cognitive data\COMT 1\Tasks\CPT" & MyFile)
With wb.Worksheets(1)
Range(A1,G113).copy
End With
With ppSht
.Range(A1,G113).PasteSpecial xlPasteFormulas
End With
pp.SaveCopyAs Filename = "MyFile_2.csv"
'Remove the wb.Close if you want the sheet to stay open (Not recommended if there are many files)
wb.Close
MyFile = Dir
loop
Try using some of this (Haven't tried it so just use it as a template). See if you can get any errors or at least if you can collect the data from the file into a array.

: Trying to open all excel files in a folder, code skips everything after Do While FileName <> ""

So I'm a bit of a VBA noob, but trying to learn.
I need my macro to open all excel files (hundreds) in a folder and extract information, to summarize all in one sheet.
After a long search, I found a sample code on msdn.microsoft.com that seemed to fit my needs:
Sub MergeAllWorkbooks()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim NRow As Long
Dim FileName As String
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
' Create a new workbook and set a variable to the first sheet.
Set SummarySheet = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
' Modify this folder path to point to the files you want to use.
FolderPath = "C:\Users\...\Desktop\Test_Summary_Folder"
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 1
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = Dir(FolderPath & "*.xl*")
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a workbook in the folder
Set WorkBk = Workbooks.Open(FolderPath & FileName)
' Set the cell in column A to be the file name.
SummarySheet.Range("A" & NRow).Value = FileName
' Set the source range to be A9 through C9.
' Modify this range for your workbooks.
' It can span multiple rows.
Set SourceRange = WorkBk.Worksheets(1).Range("A9:C9")
' Set the destination range to start at column B and
' be the same size as the source range.
Set DestRange = SummarySheet.Range("B" & NRow)
Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
SourceRange.Columns.Count)
' Copy over the values from the source to the destination.
DestRange.Value = SourceRange.Value
' Increase NRow so that we know where to copy data next.
NRow = NRow + DestRange.Rows.Count
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = Dir()
Loop
' Call AutoFit on the destination sheet so that all
' data is readable.
SummarySheet.Columns.AutoFit
End Sub
I'd like to change some parts like copying to a sheet within the workbook instead of creating a new one, and need to add a new worksheet with formulas to the workbooks before copying data, but those are bonus questions. First:
The macro only opens a new workbook, then skips everything after
Do While FileName <> "".
Does anyone have an idea why?
To clarify, there are, in fact, excel files in the test folder.
Thanks in advance :-)
You are missing a backslash:
Try
FileName = Dir(FolderPath & "\*.xl*")

Excel merge range from Macro run XLSB files into one

I have multiple (sometimes 100+) xlsb files that the user is wanting to copy row 14 from Sheet8 from all files into one workbook/worksheet.
I am able to perform this function; however the results end up showing 0's for all of the calculated fields within the xlsb files
The xlsb files are macro run
In my code to open the file looks like this:
'This one works to open but doesn't run through Macro
Set WorkBk = Workbooks.Open(FolderPath & FileName)
I updated the code with this; but then the next lines after it will not run, I believe because it is looking to "SET" and I am unsure how to perform this
'This one opens and runs macro but then fails at Set SourceRange
Workbooks.Open(FolderPath & FileName).RunAutoMacros Which:=xlAutoOpen
When I attempt to add .RunAutoMacros Which:=xlAutoOpen after the first code I get a Compile error: Expected: end of statement
'This one works to open but doesn't run through Macro
Set WorkBk = Workbooks.Open(FolderPath & FileName).RunAutoMacros Which:=xlAutoOpen
Here is the full code:
Sub MergeAllWorkbooks()
Dim SummarySheet As Worksheet
Dim FolderPath As String
Dim NRow As Long
Dim FileName As String
Dim WorkBk As Workbook
Dim SourceRange As Range
Dim DestRange As Range
Dim auto_open As String
Application.Calculation = xlCalculationAutomatic
' Create a new workbook and set a variable to the first sheet.
Set SummarySheet = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
' Modify this folder path to point to the files you want to use.
FolderPath = "C:\Users\dredden2\Documents\SHAREPOINT ARCHIVING\PAGESETUP\TEST\"
' NRow keeps track of where to insert new rows in the destination workbook.
NRow = 2
' Call Dir the first time, pointing it to all Excel files in the folder path.
FileName = DIR(FolderPath & "*.xlsb")
' Loop until Dir returns an empty string.
Do While FileName <> ""
' Open a workbook in the folder
'This one works to open but doesn't run through Macro
Set WorkBk = Workbooks.Open(FolderPath & FileName)
' Set the cell in column A to be the file name.
SummarySheet.Range("A" & NRow).Value = FileName
' Set the source range to be A9 through C9.
' Modify this range for your workbooks.
' It can span multiple rows.
Set SourceRange = WorkBk.Sheets("Retrospective Results").Range("B14:BF14")
' Set the destination range to start at column B and
' be the same size as the source range.
Set DestRange = SummarySheet.Range("B" & NRow)
Set DestRange = DestRange.Resize(SourceRange.Rows.Count, _
SourceRange.Columns.Count)
' Copy over the values from the source to the destination.
DestRange.Value = SourceRange.Value
' Increase NRow so that we know where to copy data next.
NRow = NRow + DestRange.Rows.Count
' Close the source workbook without saving changes.
WorkBk.Close savechanges:=False
' Use Dir to get the next file name.
FileName = DIR()
Loop
' Call AutoFit on the destination sheet so that all
' data is readable.
SummarySheet.Columns.AutoFit
End Sub
The final answer was:
Application.Run _
"'" & FileName & "'!auto_open"

Resources