Convert from CSV to XLSX and save with same file name - vba

I have a series of CSV files that come to me bundled in a folder simply named for the month. I've got code working to find them, open them, parse them and I'm having trouble saving them the way I want to. What I'm aiming at is saving as the same file name as it was just in the new and parsed format.
Sub OpenCSVs_2()
Dim MyFiles As String, ThisMonth As String, Convert As String
Dim startPath As String
ThisMonth = Format(Date, "mmmm")
startPath = "C:\Users\ME\Desktop\CSV find convert tests\" & ThisMonth & "\"
MyFiles = Dir(startPath & "*.csv")
Convert = Dir(startPath & "*xlsx")
Do While MyFiles <> ""
Workbooks.Open startPath & MyFiles
Call Parse1
ActiveWorkbook.SaveAs Filename:="startPath & Convert", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
MyFiles = Dir '<----------------error happens here
Loop
End Sub
The above actually does something and creates an xlsm file names "startPath & Convert". I'm sure the solution is right in front of me.

As with my previous post, you are putting your variables in quotes which then turns it into a string. so first, remove the quotes on startPath & MyFiles, then just replace the extension using the function Replace. I also added the Workbook object as you should avoid using Activeworkbook as it can cause issues.
Sub OpenCSVs_2()
Dim MyFiles As String, ThisMonth As String
Dim startPath As String
Dim wb As Workbook
ThisMonth = Format(Date, "mmmm")
startPath = "C:\Users\ME\Desktop\CSV find convert tests\" & ThisMonth & "\"
MyFiles = Dir(startPath & "*.csv")
Do While MyFiles <> ""
Set wb = Workbooks.Open(startPath & MyFiles)
Call Parse1
wb.SaveAs Filename:=startPath & Replace(MyFiles, ".csv", ".xlsx"), FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
MyFiles = Dir
Loop
End Sub

Related

Look for specific files in folder w/ VBA

I have a macro that loops through each file in a folder and do some things if the file has the today's date in its name.
Here is a piece of the code:
For Each objFile In objFolder.Files
If Left(objFile.Name, 8) = Format(Date, "dd-mm-yy") Then
currSheet = Mid(objFile.Name, 10, 4)
Sheets(currSheet).Activate
'LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
'ActiveSheet.Range("A1:D" & LastRow).Clear
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & FolderName & objFile.Name _
, Destination:=Range("$A$1"))
.Name = Left(objFile.Name, Len(objFile.Name) - 4)
'.
'.
'.
End If
Next objFile
I've just realized that it takes around 60 seconds to find the today's files, because it loops through all files in folder (around 0.1 second per file, but there's a lot of files).
I'd like to find files with the following names (only for today's date), I will run this macro once a day, for example:
30-07-18 CA01 NEGS.txt
30-07-18 CA02 NEGS.txt
30-07-18 CA03 NEGS.txt
30-07-18 CA04 NEGS.txt
So I know the name pattern.
There's a maximum of 4 files in the same date.
So it would be great if I could search only these files (and check if it exists), instead of loop through all files. Is is possible to do it? Any help will be appreciated!
The Dir function accepts wildcards, and can return the file names that match a specified pattern. Here's an example...
Option Explicit
Sub test()
Dim strPath As String
Dim strFile As String
Dim strPattern As String
strPattern = Format(Date, "dd-mm-yy")
strPath = "C:\Users\Domenic\Desktop\"
strFile = Dir(strPath & strPattern & "*.txt", vbNormal)
Do While Len(strFile) > 0
'Do stuff
'
'
strFile = Dir
Loop
End Sub

Automated sorting of files into folders using excel VBA

I am currently trying to put a macro together to sort files into folders based on a filename. I am locked into using VBA due to the system we are on.
For example sorting just the excel documents from below present in C:\ :
123DE.xls
124DE.xls
125DE.xls
124.doc
123.csv
into the following folder paths:
C:\Data\123\Data Extract
C:\Data\124\Data Extract
C:\Data\125\Data Extract
The folders are already created, and as in the example are named after the first x characters of the file. Batches of 5000+ files will need to be sorted into over 5000 folders so im trying to avoid coding for each filename
I am pretty new to VBA, so any guidance would be much appreciated. So far I have managed to move all the excel files into a single folder, but am unsure how to progress.
Sub MoveFile()
Dim strFolderA As String
Dim strFolderB As String
Dim strFile as String
strFolderA = "\\vs2-alpfc\omgusers7\58129\G Test\"
strFolderb = "\\vs2-alpfc\omgusers7\58129\G Test\1a\"
strFile = Dir(strFolderA & "*.xlsx*")
Do While Len(strFile) >0
Name StrFolderA & strFile As strFolderB & strFile
strFile = Dir
Loop
End Sub
Greg
EDIT
Sub MoveFile()
Dim strFolderA As String
Dim strFile As String
Dim AccNo As String
strFolderA = "\\vs2-alpfc7\omgUSERS7\58129\G Test\"
strFile = Dir(strFolderA & "*.xlsx*")
Do While Len(strFile) > 0
AccNo = Left(strFile, 2)
Name strFolderA & strFile As strFolderA & "\" & AccNo & "\Data Extract\" & strFile
strFile = Dir
Loop
End Sub
Thanks folks, are a few more bits and pieces i want to add, but functionality is there!
Sub DivideFiles()
Const SourceDir = "C:\" 'where your files are
Const topdir = "\\vs2-alpfc\omgusers7\58129\G Test\"
Dim s As String
Dim x As String
s = Dir(SourceDir & "\*.xls?")
Do
x = Left(s, 3) 'I assume we're splitting by first three chars
Name SourceDir & s As topdir & s & "\" & s
Loop Until s = ""
End Sub
If I understand you correctly, the problem is deriving the new fullpathname from the file name to use as the newpathname argument of the Name function.
If all of your files end with DE.XLS* you can do something like:
NewPathName = C:\Data\ & Split(strFile, "DE")(0) & "\Data Extract\" & strFile
You could use Filesystem object (tools > references > microsoft scripting runtime
This does a copy first then delete. You can comment out delete line and check copy is safely performed.
If on Mac replace "\" with Application.PathSeparator.
Based on assumption, as you stated, that folders already exist.
Option Explicit
Sub FileAway()
Dim fileNames As Collection
Set fileNames = New Collection
With fileNames
.Add "123DE.xls"
.Add "124DE.xls"
.Add "125DE.xls"
.Add "124.doc"
.Add "123.csv"
End With
Dim fso As FileSystemObject 'tools > references > scripting runtime
Set fso = New FileSystemObject
Dim i As Long
Dim sourcePath As String
sourcePath = "C:\Users\User\Desktop" 'where files currently are
For i = 1 To fileNames.Count
If Not fso.FileExists("C:\Data\" & Left$(fileNames(i), 3) & "\Data Extract\" & fileNames(i)) Then
fso.CopyFile (sourcePath & "\" & fileNames(i)), _
"C:\Data\" & Left$(fileNames(i), 3) & "\Data Extract\", True
fso.DeleteFile (sourcePath & "\" & fileNames(i))
End If
Next i
End Sub

Showing excel save as dialog box and prefill with cell reference

With no coding knowledge, I have attempted to use some code found here: Automatically name a file based on cell data when saving a spreadsheet?. Thanks to Jean-François Corbett
I have adapted as follows to show the dialog box:
Sub SaveAsString()
Dim strPath As String
Dim strFolderPath As String
strFolderPath = "N:\PROJECTS\"
strPath = strFolderPath & _
Sheet1.Range("B2").Value & "_" & _
Sheet1.Range("B6").Value & "_" & _
Sheet1.Range("X1").Value & "-JS-1" & ".xlsm"
Application.Dialogs(xlDialogSaveAs).Show strPath
ActiveWorkbook.SaveAs FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
I am opening an .xltm file, and attempting to save with the ability to select the subfolder of N:\PROJECTS\ with the combination of cell references shown.
The dialog box appears fine, already showing N:\PROJECTS. However, it does not fill the file name, unless the file is first saved as a .xlsm. It then always attempts to overwrite as well.
This worked for me, utilizing a slightly different code technique.
Option Explicit
Sub SaveAsString()
Dim strPath As String
Dim strFolderPath As String
ChDir "N:\PROJECTS\" 'set directory with this line
With Sheet1
strPath = .Range("B2").Value
strPath = strPath & "_" & .Range("B6").Value
strPath = strPath & "_" & .Range("X1").Value
strPath = strPath & "-JS-1.xlsm"
End With
Application.Dialogs(xlDialogSaveAs).Show strPath 'load file name with this argument
ActiveWorkbook.SaveAs FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
The main issue remaining was that opening from a template didn't automatically save as .xlsm. Apparently Application.Dialogs doesn't support file filters, so the problem is better solved with GetSaveasFileName.
Full code as follows:
Sub SaveAsString()
Dim strPath As String
Dim strFolderPath As String
strFolderPath = "N:\PROJECTS\"
strPath = strFolderPath & _
Sheet1.Range("B2").Value & "_" & _
Sheet1.Range("B6").Value & "_" & _
Sheet1.Range("X1").Value & "-JS-1" & ".xlsm"
fileSaveName = Application.GetSaveAsFilename(strPath _
, fileFilter:="Excel Files (*.xlsm), *.xlsm")
End Sub

VBA to find all CSV files in a Variable Folder name

I have a project to create VBA to find and open all CSV files in a folder that is named the current month. I found some stuff online that seemed close but not quite. They will eventually be converted to XLSX files and parsed. That part I have. The macro that converts, parses and saves will be housed in a different file along the same path but not as "deep".
So on my Desktop is a folder name "CSV find test". Inside are two folders "Feburary" and "March". I need it to open all csv files in the most recent month. I have the rest of the syntax. . . . .
I wouldn't imagine that it would take a huge amount of syntax. Thanks for any direction.
Sub OpenFile()
FileMonth = Month(Date)
FileDate = Format(Date, "mmmm")
FilePath = "C:\Users\Me\Desktop\CSV find convert tests\" & FileMonth & "\" & FileDate & ".xls"
Workbooks.Open Filename:="FilePath" <- - - - error happens here.
End Sub
I don't think you really understand how a variable works as you keep putting it in a string. If you put something in double quotes it creates a string. Below is how you can add the month to the string via the variable.
Sub OpenCSVs()
Dim MyFiles As String, ThisMonth As String
Dim startPath As String
ThisMonth = Format(Date, "mmmm")
startPath = "C:\Users\ME\Desktop\CSV find convert tests\" & ThisMonth & "\"
MyFiles = Dir(startPath & "*.csv")
Do While MyFiles <> ""
Workbooks.Open startPath & MyFiles
'Do stuff to it will go here
'ActiveWorkbook.Close SaveChanges:=True (Deactivated for now)
MyFiles = Dir
Loop
End Sub

Excel VBA Convert .csv to Excel File

I have a folder which has .csv files, .xls files, and xlsx files. The below code is a portion of an overall project (when I remove the below code, the remaining code achieves what I want). A large chunk of the code was compiled from somewhere (here and around the internet). What I want the code to do is open only the .csv files in the folder, convert them to an Excel file, close the files, and then delete the .csv files in the folder. What ends up happening with the code is that one or both of the files created by the code are deleted from the folder, and I am left with nothing. Thanks in advance for any help.
Sub Test()
'
' Test Macro
'
'Set variables for the below loop
Dim MyFolder As String
Dim MyFile As String
Dim GetBook As String
Dim GetBook2 As String
Dim MyCSVFile As String
Dim KillFile As String
MyFolder = "REDACTED"
MyFile = Dir(MyFolder & "\*.xls")
MyCSVFile = Dir(MyFolder & "\*.csv")
'Open all of the .csv files in the folder and convert to .xls
Do While MyCSVFile <> ""
Workbooks.Open Filename:=MyFolder & "\" & MyCSVFile
GetBook = ActiveWorkbook.Name
GetBook2 = Left(GetBook, Len(GetBook) - 4)
ActiveSheet.Name = "Sheet1"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=GetBook2, FileFormat:=56
ActiveWorkbook.Close False
Kill MyFolder & "\" & GetBook
Loop
End Sub
You are not calling the Dir function to get the next file.
Sub Test()
'Set variables for the below loop
Dim myFolder As String
Dim getBook As String
Dim myCSVFile As String
Application.DisplayAlerts = False
myFolder = Environ("TEMP") & Chr(92) & "REDACTED"
myCSVFile = Dir(myFolder & "\*.csv")
Do While myCSVFile <> ""
Workbooks.Open Filename:=myFolder & "\" & myCSVFile
getBook = ActiveSheet.Name '<~ Sheet1 of an opened CSV is the name of the CSV
ActiveSheet.Name = "Sheet1"
ActiveWorkbook.SaveAs Filename:=myFolder & Chr(92) & getBook, FileFormat:=56
ActiveWorkbook.Close False
Kill myFolder & Chr(92) & myCSVFile '<~~ delete the CSV, not the workbook
myCSVFile = Dir '<~~ this is important to get the next file in the folder listing
Loop
End Sub
The only worksheet in an opened CSV is named for the CSV (without the .CSV extension) so that can be used in the Workbook.SaveAs method. I've used xlOpenXMLWorkbook as the SaveAs FileFormat type.