Ask client which file you would like to process - excel

I am trying to build a Macro to help my teammate to update the file automictically
if I want to modify it to...
Ask the client which multiple file you want to convert?
looping and convert the file
END
here is the code I copy from internet.
Thank you!
Sub AllEDIFiles()
Dim folderPath As String
Dim filename As String
Dim wb As Workbook
folderPath = "C:\Users\"'change to suit
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
filename = Dir(folderPath & "*.csv")
Do While filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & filename)
Call EDI
filename = Dir
Loop
Application.ScreenUpdating = True
MsgBox ("Done!")
End Sub

To get the macro to open a window for the user to select a file you could use:
strFileToOpen = Application.GetOpenFilename _
(Title:="Please choose a file to open", _
FileFilter:="Excel Files *.xls* (*.xls*),")

Related

Converting multiple xlsl files to xls (97-2003 Worksheet) extension without changing the names

I am trying to loop through all the 'xlsx' files in a folder and convert them to 'xls' ( Excel 97-2003 Worksheet) format. I use the following codes but then the output files are still saved as 'xlsx' instead of 'xls'. I am a beginner and looking to learn more from others. Thanks for your help!
Sub Convert()
Dim strPath As String
Dim strFile As String
Dim strfilenew As String
Dim xWbk As Workbook
Dim xSFD, xRFD As FileDialog
Dim xSPath As String
Dim xRPath As String
Set xSFD = Application.FileDialog(msoFileDialogFolderPicker)
With xSFD
.Title = "Please select the folder contains the xls files:"
.InitialFileName = "C:\"
End With
If xSFD.Show <> -1 Then Exit Sub
xSPath = xSFD.SelectedItems.Item(1)
Set xRFD = Application.FileDialog(msoFileDialogFolderPicker)
With xRFD
.Title = "Please select a folder for outputting the new files:"
.InitialFileName = "C:\"
End With
If xRFD.Show <> -1 Then Exit Sub
xRPath = xRFD.SelectedItems.Item(1) & "\"
strPath = xSPath & "\"
strFile = Dir(strPath & "*.xlsx")
strfilenew = Dir(strPath & "*.xls")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While strFile <> ""
If Right(strFile, 4) = "xlsx" Then
Set xWbk = Workbooks.Open(Filename:=strPath & strfilenew)
xWbk.SaveAs Filename:=xRPath & strfilenew, _
FileFormat:=xlExcel18
xWbk.Close SaveChanges:=True
End If
strFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
There was a bit of a mix-up in your file naming, basically as evidenced by the several double-declarations that I removed. The really big mistake was here, Set xWbk = Workbooks.Open(Filename:=strPath & strfilenew) where you tried to open the old workbook by the new name. I think the confusion started here "Please select the folder contains the xls files:". Of course, this is the folder with the XLSX files. The recommended antidote is to use "meaningful" variable names but you chose to speak in riddles (like xSFD) which makes coding more difficult.
However, the code below is largely yours, and it does work.
Sub Convert()
' 230
Dim Spath As String ' path to read from (XLSX files)
Dim Rpath As String ' path to write to (XLS files)
Dim strFile As String ' loop variable: current file name
Dim Wbk As Workbook ' loop object: current workbook(strFile)
Dim Sp() As String ' split array of strFile
Dim strFileNew As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select the folder contains the XLSX files:"
.InitialFileName = "C:\"
If .Show <> -1 Then Exit Sub
Spath = .SelectedItems.Item(1) & "\"
End With
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder for outputting the new files:"
.InitialFileName = "C:\"
If .Show <> -1 Then Exit Sub
Rpath = .SelectedItems.Item(1) & "\"
End With
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
strFile = Dir(Spath & "*.xlsx")
Do While strFile <> ""
If Right(strFile, 4) = "xlsx" Then
Sp = Split(strFile, ".")
Sp(UBound(Sp)) = "xls"
strFileNew = Join(Sp, ".")
Set Wbk = Workbooks.Open(Filename:=Spath & strFile)
Wbk.SaveAs Filename:=Rpath & strFileNew, FileFormat:=xlExcel8
Wbk.Close SaveChanges:=True
End If
strFile = Dir
Loop
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub
Observe that the new file name is created by splitting the old name on periods, changing the last element, and reassembling the modified array.

VBA Loop through files in a directory, save as csv in another directory, skip if file exists

I have a bit of code that loops through a bunch of files in a folder, runs a macro on each of them, and then saves them as a .csv file in a different folder. The process runs fine with if the destination csv folder is empty. What I want to do is skip the process if the .csv file already exists. The problem with the code below, is that the Filename = Dir() returns a null value and the loop ends if the .csv file exists. So how do I continue looping through the other files in the first folder?
Sub ProcessFiles()
Dim Filename, Pathname, strFileExists As String
Dim wb As Workbook
Application.ScreenUpdating = False
Pathname = ActiveWorkbook.Path & "\Files\"
Filename = Dir(Pathname & "*.xlsx")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
length = Len(ActiveWorkbook.Name)
Name = Left(ActiveWorkbook.Name, length - 5)
CSVName = ActiveWorkbook.Path & "\CSV Files\" & Name & ".csv"
strFileExists = Dir(CSVName)
If strFileExists = "" Then
Transform wb 'Run Transform function
wb.SaveAs Filename:=CSVName, FileFormat:=xlCSVMSDOS, CreateBackup:=False
wb.Close SaveChanges:=False
Filename = Dir()
Else
wb.Close SaveChanges:=False
Filename = Dir()
End If
Loop
End Sub
I think braX is right: the problem is you are using Dir twice. This seems to be working for me:
Sub ProcessFiles()
Dim Filename, Pathname, strFileExists As String
Dim wb As Workbook
Dim IntFileNumber As Integer
Dim IntCounter01 As Integer
Dim Length As Byte
Dim Name As String
Dim CSVName As String
Application.ScreenUpdating = False
Pathname = ActiveWorkbook.Path & "\Files\"
Filename = Dir(Pathname & "*.xlsx")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
Length = Len(ActiveWorkbook.Name)
Name = Left(ActiveWorkbook.Name, Length - 5)
CSVName = ActiveWorkbook.Path & "\CSV Files\" & Name & ".csv"
strFileExists = Dir(CSVName)
If strFileExists = "" Then
Transform wb 'Run Transform function
wb.SaveAs Filename:=CSVName, FileFormat:=xlCSVMSDOS, CreateBackup:=False
wb.Close SaveChanges:=False
Filename = Dir(Pathname & "*.xlsx")
IntFileNumber = IntFileNumber + 1
For IntCounter01 = 1 To IntFileNumber
Filename = Dir()
Next
Else
wb.Close SaveChanges:=False
Filename = Dir(Pathname & "*.xlsx")
IntFileNumber = IntFileNumber + 1
For IntCounter01 = 1 To IntFileNumber
Filename = Dir()
Next
End If
Loop
End Sub
Basically i reset the Filename and re-play Dir as many time as needed to reach the wanted file.
I've added some declarations too. You might also want to turn true the ScreenUpdating at the end of the subroutine, but that's up to you.

Save .xlsx files in a folder to .csv files

I tried this script to convert xlsx files to csv.
I want the old files to be in the folder and the name on csv file to be exact as xlsx file.
I am getting . extra on the csv extension like filename..csv.
Sub ConvertCSVToXlsx()
Dim myfile As String
Dim oldfname As String, newfname As String
Dim workfile
Dim folderName As String
Application.DisplayAlerts = False
Application.ScreenUpdating = False
' Capture name of current file
myfile = ActiveWorkbook.Name
' Set folder name to work through
folderName = "C:\Test\"
' Loop through all CSV filres in folder
workfile = Dir(folderName & "*.xlsx")
Do While workfile <> ""
' Open CSV file
Workbooks.Open Filename:=folderName & workfile
' Capture name of old CSV file
oldfname = ActiveWorkbook.FullName
' Convert to XLSX
newfname = folderName & Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4) & ".CSV"
ActiveWorkbook.SaveAs Filename:=newfname, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWorkbook.Close
' Delete old CSV file
Kill oldfname
Windows(myfile).Activate
workfile = Dir()
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Pretty close.
Your comments are a bit confusing in the code.
If you are going to use left(len()-4 then you need to change the part to add csv without the period.
newfname = oldfname & "CSV"
Just a bit of an edit with the saveas line
You don't kill the original workbook, that deletes it from the folder.
The original workbook is no longer opened because you saved it as a new filename.
Sub ConvertCSVToXlsx()
Dim myfile As String
Dim oldfname As String, newfname As String
Dim workfile
Dim folderName As String
Dim wb As Workbook
Application.DisplayAlerts = False
Application.ScreenUpdating = False
' Capture name of current file
myfile = ActiveWorkbook.Name
' Set folder name to work through
folderName = "C:\New folder\"
' Loop through all CSV filres in folder
workfile = Dir(folderName & "*.xlsx")
Do While workfile <> ""
' Open CSV file
Workbooks.Open Filename:=folderName & workfile
Set wb = ActiveWorkbook
' Capture name of old CSV file
oldfname = Left(wb.FullName, Len(wb.FullName) - 4)
' Convert to XLSX
newfname = oldfname & "CSV"
wb.SaveAs Filename:=newfname, FileFormat:=xlCSV, CreateBackup:=False
wb.Close
workfile = Dir()
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Loop Freezing Excel After Printing

I have a spreadsheet that creates a CSV file and deposits the CSV file in a folder next to the original file. The spreadsheet seems to work fine. When you have your data entered, you click export, and a CSV file is put in a folder called "Uploads" that is next to the original file.
The issue is when I use the quick print button on my Excel quick access toolbar. When I click the quick print button, everything seems to print fine. However, as soon as I close the file, (EDIT: ALL Printing seems to be freezing the file. As soon as the file is closed) Excel then goes into a freeze where it looks like it is trying to run some code? I am a novice in VBA so I am not sure what is happening, all I know is that after my file is closed, Excel freezes up and I have to restart Excel. I do not even have any macros or VBA for an Excel close or Excel open trigger.
Can anyone recreate the issue and give me insight into how my code might be doing this?
Private Sub Export_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim MyPath As String
Dim MyFileName As String
'The path and file names:
MyPath = ActiveWorkbook.Path & "\Uploads"
MyFileName = "" & Range("a2") & "_Upload"
On Error GoTo Ending
'Makes sure the path name ends with "\":
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
'Makes sure the filename ends with ".csv"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
'Copies the sheet to a new workbook:
Sheets("UploadData").Copy
'The new workbook becomes Activeworkbook:
With ActiveWorkbook 'Saves the new workbook to given folder / filename:
.SaveAs FileName:= _
MyPath & MyFileName, _
FileFormat:=xlCSV, _
CreateBackup:=False 'Closes the file
.Close False
End With
ChDir MyPath
Workbooks.Open FileName:= _
MyPath & "\" & MyFileName & """"
ActiveWorkbook.Save
ActiveWorkbook.Close
GoTo Skip
Ending:
MsgBox ("ERROR! Please make sure you have a folder named Uploads next to the template file")
ActiveWorkbook.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Skip:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
This actually shouldn't work at all, regardless of what you do before you run it. First, you ensure that MyPath ends with a \ here...
'Makes sure the path name ends with "\":
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
...but then when you (re)build the same path below you're inserting a second \:
Workbooks.Open FileName:= _
MyPath & "\" & MyFileName & """"
This should always fail. You can avoid this entire problem with paths by using the Scripting.FileSystemObject's .BuildPath function:
'Requires a reference to Microsoft Scripting Runtime.
Dim filePath As String, fso As New Scripting.FileSystemObject
filePath = fso.BuildPath(ThisWorkbook.Path, MyFileName)
You can also use this for the file extension:
If LCase$(fso.GetExtensionName(MyFileName)) <> "csv" Then
MyFileName = MyFileName & ".csv"
End If
Note that this test will never be true...
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
...because MyFileName will always end with "load":
MyFileName = "" & Range("a2") & "_Upload"
Also, you should remove all the references to ActiveWorkbook. I have no idea why printing would effect this, but there isn't anything else I can identify that should be an issue. I'd structure it more like this (error handler removed for clarity - don't put it back until you're finished debugging it):
'Add a reference to Microsoft Scripting Runtime.
Private Sub Export_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
With New Scripting.FileSystemObject
Dim filePath As String
Dim targetDir As String
targetDir = .BuildPath(ThisWorkbook.Path, "Uploads")
If Not .FolderExists(targetDir) Then
MsgBox ("ERROR! Please make sure you have a folder named Uploads next to the template file")
Exit Sub
End If
filePath = .BuildPath(targetDir, ActiveSheet.Range("A2").Value & "_Upload.csv")
End With
'Copies the sheet to a new workbook:
Dim csv As Workbook
Set csv = Application.Workbooks.Add
With csv
ThisWorkbook.Sheets("UploadData").Copy .Sheets(1)
.SaveAs Filename:=filePath, _
FileFormat:=xlCSV, _
CreateBackup:=False 'Closes the file
.Close xlDoNotSaveChanges
End With
'Reopen and re-save to fix formatting.
Set csv = Workbooks.Open(filePath)
csv.Close xlSaveChanges
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Dir issue when saving a workbook as *.xml to a subfolder

I have a small script allowing me to traverse through all xslx files in the current folder, and saving them all as xml worksheets.
That works fine, but I'd like to save them in a subfolder, and that's where things go wrong as I'm always saving the same file again. I'm not too familiar with the Dir syntax, so if someone could help me out a bit I would be really grateful.
This part works as expected :
Sub XLS2XML()
Application.DisplayAlerts = False
Dim folderPath As String
Dim Report As String
Dim ReportName As String
Dim XMLLocation As String
Dim XMLReport As String
Dim WB As Workbook
'set path to current location
folderPath = ThisWorkbook.Path
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
'loop through all xlsx files
Report = Dir(folderPath & "*.xlsx")
Do While Report <> ""
Set WB = Workbooks.Open(folderPath & Report)
'get the file name without path
ReportName = Split(Report, ".")(0)
XMLLocation = folderPath
XMLReport = XMLLocation & ReportName & ".xml"
'save the file as xml workbook
ActiveWorkbook.SaveAs filename:=XMLReport, _
FileFormat:=xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
'close and next
WB.Close False
Report = Dir
Loop
MsgBox "All XML files have been created"
Application.DisplayAlerts = True
End Sub
and this one fails on me :
Sub XLS2XML()
Application.DisplayAlerts = False
Dim folderPath As String
Dim Report As String
Dim ReportName As String
Dim XMLLocation As String
Dim XMLReport As String
Dim WB As Workbook
'set path to current location
folderPath = ThisWorkbook.Path
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
'loop through all xlsx files
Report = Dir(folderPath & "*.xlsx")
Do While Report <> ""
Set WB = Workbooks.Open(folderPath & Report)
'get the file name without path and save it in xml folder
ReportName = Split(Report, ".")(0)
XMLLocation = folderPath & "xml"
XMLReport = XMLLocation & "\" & ReportName & ".xml"
'create xml folder if it doesn't exist yet
If Len(Dir(XMLLocation, vbDirectory)) = 0 Then
MkDir XMLLocation
End If
'save the file as xml workbook
ActiveWorkbook.SaveAs filename:=XMLReport, _
FileFormat:=xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
'close and next
WB.Close False
Report = Dir
Loop
Any idea where my syntax goes wrong ? Also, is it possible to do the same thing in silent mode ? So without opening the workbooks ?
Thanks !
Your issue is that you are using a second Dir within your initial Dir loop to test and create the xml subdirectory.
You can - and should move this outside the loop - especially as it is a one-off test and shouldn't be looped to begin with. Something like this below
(You otherwise used Dir fine, as per my simple wildcard code example in Loop through files in a folder using VBA?)
Sub XLS2XML()
Application.DisplayAlerts = False
Dim folderPath As String
Dim Report As String
Dim ReportName As String
Dim XMLlocation As String
Dim XMLReport As String
Dim WB As Workbook
'set path to current location
folderPath = ThisWorkbook.Path
XMLlocation = folderPath & "xml"
If Len(Dir(XMLlocation, vbDirectory)) = 0 Then MkDir XMLlocation
If Right$(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
'loop through all xlsx files
Report = Dir(folderPath & "*.xlsx")
Do While Len(Report) > 0
Set WB = Workbooks.Open(folderPath & Report)
'get the file name without path and save it in xml folder
ReportName = Split(Report, ".")(0)
XMLReport = XMLlocation & "\" & ReportName & ".xml"
'save the file as xml workbook
WB.SaveAs Filename:=XMLReport, _
FileFormat:=xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
'close and next
WB.Close False
Report = Dir
Loop
End Sub

Resources