Converting a csv file to Excel (with columns as text) using VBA - excel

I have a csv file, for example with data as below (a.csv) to convert into Excel.
In the second column the leading 0s are truncated.
Is there a way to define the second column as text before importing the csv into Excel?
I dont want to append "`" or any characters to the second column as suggested in many solutions.
a.csv
--------
123,001232323
456,004567772
I have the code below.
srccsvfile = "C:\a.csv"
tgtxlsfile = "C:\a.xls"
'Instantiate Excel
Set objExcel = CreateObject("Excel.Application")
'open the CSV file
Set objWorkBook = objExcel.Workbooks.open(srccsvfile)
Set objWorksheet1 = objWorkbook.Worksheets(1)
objWorksheet1.Columns("A:I").AutoFit
objWorksheet1.Columns("B").NumberFormat="#"
'Save the file as excel workbook
objWorkBook.SaveAs tgtxlsfile, 39
'close workbook
objWorkBook.Close False
'quit excel
objExcel.Quit
'clean up
Set objWorkBook = Nothing
Set objExcel = Nothing

Change the cell's format to 'text' rather than 'general' or 'number' and Excell will leave it alone.

I am not sure where from you tried to execute your code. Here is what you could do from Excel VBA; executing the code from elsewhere would require few tweaks already mentioned in your code...
Sub importCSVFile()
Dim objWorkBook As Workbook
Dim myFile as String
srccsvfile = "C:\temp\a.csv"
Workbooks.OpenText Filename:=myFile, Origin:=-535, StartRow:=1, _
DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter _
:=False, Tab:=False, Semicolon:=False, Comma:=False, Space:=False, _
Other:=True, OtherChar:=",", FieldInfo:=Array(Array(1, 1), Array(2, 2)), _
TrailingMinusNumbers:=True
Set objWorkBook = ActiveWorkbook
'do something with active WorkBook
End Sub

Related

Copy pasting from different CSVs to one XLSX file

I am trying to succeed the following in VBA:
Open each file in the folder ( 1 by 1 )
Since all files are CSVs, I'd like to make them into more columns to gather the data I need.
I'd like to copy-paste these into one specific excel. These are around 300 rows.
In that specific Excel I'd like to have them pasted under each other.
What I have already tried:
The method to find all those files I need.
Make CSV datas into columns.
Copy-paste method.
Find the first empty row down under.
The problem is: I don't have enough knowledge for the macro to do it to all CSVs.
Please see my code below where I got so far:
Sub pm_logger()
Application.ScreenUpdating = False
Dim bookDest As Workbook
Dim bookFrom As Workbook
Dim lDestLastRow as Long
Dim sh As Worksheet
Workbooks.Open "P:\logs\logstorage.xlsx"
Workbooks.Open "P:\logs\logfile.csv"
Set bookDest = Workbooks("logstorage.xlsx")
Set bookFrom = Workbooks("logfile.csv")
bookFrom.Activate
Set sh = Worksheets(1)
With sh
Set Rng = .Range("A5:A305")
Set Rng = .Range(Rng, .Cells(.Rows.Count, Rng.Column).End(xlUp))
Rng.TextToColumns Destination:=Rng, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True, _
Space:=False, _
Other:=False, _
FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
TrailingMinusNumbers:=True
End With
bookFrom.Worksheets(1).Range("A5:K304").Copy
lDestLastRow = bookDest.Cells(bookDest.Rows.Count, "A").End(xlUp).Offset(1).Row
bookDest.Range("A" & xlDestLastRow).PasteSpecial Paste:=xlPasteValues
'Workbooks("logstorage.xlsx").Close SaveChanges:=True
Application.ScreenUpdating = True
End Sub
Thank you very much in advance!
To get this done, you first need a way to get all your .csv files loaded into your macro. This can be done a few ways, but I suggest a file picker to load them all into a collection:
Dim picker As Office.FileDialog
Dim mycsvs As New Collection
Dim file As Variant
Set picker = Application.FileDialog(msoFileDialogFilePicker)
With picker
.Filters.Clear
.Filters.Add "CSV files", "*.csv", 1
.AllowMultiSelect = True
.InitialFileName = "P:logs\"
If .Show = True Then
For Each file In .SelectedItems
mycsvs.Add file
Next file
End If
End With
Now you have the collection mycsvs which holds all the files you selected to be processed. Then all you need after that is to loop over them with the code you have already written:
Workbooks.Open "P:\logs\logstorage.xlsx"
For Each file In mycsvs
Set bookDest = Workbooks("logstorage.xlsx")
Set bookFrom = Workbooks.open(file)
'your code here from "Bookfrom.Activate"
bookFrom.Close SaveChanges:= False
Next file
'Workbooks("logstorage.xlsx").Close SaveChanges:=True

Copy a .txt file to excel

I am trying to copy multiple txt file into excel but having a little issue on the following:
Sub devise(FICHIER, FEUILLE)
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets(FEUILLE)
Dim wbcopy As Workbook
ChDir "R:\Oco_R\Valoco"
Workbooks.OpenText Filename:="R:\Oco_R\Valoco\" & FICHIER, Origin:= _
xlWindows, StartRow:=1, DataType:=xlFixedWidth, FieldInfo:= _
Array(Array(0, 1), Array(6, 1), Array(26, 1), Array(35, 1), Array(46, 1), _
Array(53, 1), Array(64, 1), Array(72, 1))
Selection.Copy
ws.Activate
ws.Range("A1").PasteSpecial
'ActiveSheet.Paste
ws.Rows("1:4").Delete Shift:=xlUp
ws.Cells.Select
Selection.Sort Key1:=Range("A1"), Order1:=xlAscending, Header:= _
xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:= _
xlTopToBottom
Application.CutCopyMode = False
ActiveWorkbook.Close
End Sub
I already defined the workbook where I would like the txt to be copied to. But I was wondering how I could DIM the txt file so that I can close it? For example FIHCIER.close, but doesn't work of course...
In the code I'm using ActiveWorkbook.Close but it is referring to my excel file which I don't want to close.
I tried using a Set wbC but haven't really succeeded...
Thank you very much for your help!
When you open a textfile using Workbooks.OpenText, Excel will create a workbook (containing one sheet) from the text file.
For some strange reasons OpenText is not implemented as function (in opposite to Workbooks.Open`), so you can't do something like
set txtFile = Workbooks.OpenText(MyTextFileName)
However, after you open the file, it is automatically the ActiveWorkbook, so you can do the following:
Dim txtFile as Workbook
Workbooks.OpenText filename:=MyTextFileName
Set txtFile = ActiveWorkbook
(...)
txtFile.close saveChanges:=False

I need to set the path in a VBA in Excel so a file can be used on multiple computers

I have an excel file that creates an order for our supplier, and I use a VBA script to copy the data to another file and format it in the manner the supplier uses. Now that is properly running, my boss wishes to use this method at our other locations. The problem is that the script is tailored to our local computer.
I need to change the path to the location the file saves in the script from our local drive:
C:\Users\*User*\Desktop\
to a generic one like this:
C:\Users\%USERNAME%\Desktop\
I've looked at several options but really am confused at the simplest manner of doing this properly.
Here is the code I am currently using:
Sub Order()
'
' Creates Order form Visual Basic control
' Visual Basic script recorded 8/27/2021 by Me
' Copies order to Supplier
'
MSG1 = MsgBox("Do you wish to create a new order?", vbYesNo, "New Order Confirmation")
If MSG1 = vbYes Then
'Copies data
Range("M1:N300").Select
Selection.Copy
Range("A3").Select
'Pastes data to text file
Workbooks.OpenText Filename:="C:\Users\*User*\Desktop\upload.txt", Origin:= _
437, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=False _
, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1)), _
TrailingMinusNumbers:=True
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
ActiveWorkbook.Save
ActiveWindow.Close
Range("A3").Select
'Closes text file
Dim wb As Workbook
Set wb = Application.Workbooks.Open("C:\Users\*User*\Desktop\upload.txt")
wb.Close
End If
'Opens web upload dialog
MSG2 = MsgBox("Do you wish to upload the order to Supplier?", vbYesNo, "Upload Confirmation")
If MSG2 = vbYes Then
Const Hyper As String = "*URL of Supplier*"
ThisWorkbook.FollowHyperlink Address:=Hyper ', NewWindow:=Tru
End If
End Sub
I usually use the code on Ron de Bruins website.
Sub Test()
Dim WshShell As Object
Dim DeskTopPath As String
Set WshShell = CreateObject("WScript.Shell")
DeskTopPath = WshShell.SpecialFolders("Desktop")
Dim wrkBk As Workbook
Set wrkBk = Workbooks.Open(DeskTopPath & "\upload.txt")
wrkBk.Save
wrkBk.Close
End Sub
Special folders are : AllUsersDesktop, AllUsersStartMenu
AllUsersPrograms, AllUsersStartup, Desktop, Favorites
Fonts, MyDocuments, NetHood, PrintHood, Programs, Recent
SendTo, StartMenu, Startup, Templates

How do I get the text from a .txt file and write it in a new sheet in the same excel file

I want a whole text file to enter into a new sheet in excel. Right now I am only getting all values in to one cell, I want it to look like in the text file. Like every row get one row in excel.
I have tried this tutorial but this doesn't get it.
https://www.excel-easy.com/vba/examples/read-data-from-text-file.html
I solved it for you who wants to know how check below
Sub GetText()
Dim SheetName As String
Dim TMPWorkBook As Workbook
Dim FilePath As String
Dim TxtFilePath As String
Dim TxtFileName As String
Set WB = ThisWorkbook
SheetName = "Test_Result"
TxtFileName = "C:\getitdone.txt"
Workbooks.OpenText Filename:= _
TxtFileName _
, Origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, Other:=True, OtherChar:="|", FieldInfo:=Array(Array(1, 1), _
Array(2, 1)), DecimalSeparator:=".", ThousandsSeparator:=",", _
TrailingMinusNumbers:=True
Set TMPWorkBook = ActiveWorkbook
Cells.Select
Selection.Copy
Workbooks("Getitdone.xlsm").Activate
Sheets.Add.Name = "Data"
Range("A1").PasteSpecial xlPasteValues
End Sub

Import daily CSV Files To Standard Excel Worksheet Locations

I want to import csv files to my own workbook. Now it creates a new workbook every time. I want the data within my csv files to go in the different sheets. Only I want the data set to 11 standard sheets cause I have 11 teams (Team A, Team B etc.). This does currently work as it creates a new workbook with 11 sheets.
I have an Excel file set up that I want to use for a project.
In this case there are several teams that export data daily to csv files.
Now, I want to import these files to my active workbook where each team will have it's own worksheet. The CSV data files will need to be imported by using a button. Then the csv data will go into the same workbook.
I found the following code on the web and it works good! The only issue with this way is that it creates a new workbook every time. Then I have to copy the data from the new generated workbook (the data per team in sheets) to my own workbook.
This copy pasting is as you can imagine quite annoying at the moment. I hope there is anyone that is good at programming and could possibly help me :) ? The code that I currently use to Import the data to a random generated workbook is as following:
Sub DataImporteren()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = ","
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="CSV Files (*.csv), *.csv", _
MultiSelect:=True, Title:="CSV Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
x = x + 1
While x <= UBound(FilesToOpen)
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
End With
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
So at the end what I need help with:
Standard workbook where I have my overview. With calculations and formulas to compare the imported data. (already have this working)
Import the data to this standard workbook instead of a this macro creating a new workbook every time.
For each team in (standard csv files) my workbook a standard sheet. CSV file: "Team A" gets imported to worksheet Team A every time I import the new updated Team A csv file etc.
I hope someone can help me as this would save me lots of time copy pasting.
The following works for me. There are a number of changes to the code in the question.
The target Workbook is set near the beginning, before the files are opened, which would change the "active" workbook. This way, there's no confusion.
The entire copying is in a For...Next loop. As far as I can tell, there's no reason for one execution, then a loop. I've used For...Next so that the x increments automatically.
The actual problem asked in the question is due to not specifying the target where the content of the csv file should be inserted. If no target range is specified, the data is placed in a new workbook. The target range is therefore set to the Worksheet(x + 1) in the target workbook; the UsedRange of the in-coming data sheet is copied (instead of the entire worksheet) - this places the data at the top left of the target worksheet.
x + 1 is used since the data should go to the second and following worksheets.
The data sheet is only closed after the copy and insertion and the variable set to Nothing. This worked more reliably in my tests.
As it stands, Excel will query whether to over-write the existing sheet content when new data is brought in. If this is not wanted, insert a line that deletes the UsedRange of each worksheet before the data is inserted.
Sub DataImporteren()
Dim FilesToOpen
Dim x As Long
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim wsData As Worksheet
Dim rngDestination As Range
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
x = 1
Set wkbAll = ActiveWorkbook
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="CSV Files (*.csv), *.csv", _
MultiSelect:=True, Title:="CSV Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
For x = 1 To UBound(FilesToOpen)
'Start at second worksheet
Set rngDestination = wkbAll.Worksheets(x + 1).Range("A1")
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
Set wsData = wkbTemp.Worksheets(1)
wsData.UsedRange.Copy rngDestination
wkbAll.Worksheets(x + 1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
wkbTemp.Close False
Set wkbTemp = Nothing
Next
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub

Resources