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

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

Related

Ask client which file you would like to process

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*),")

How to close a workbook when i already set the filename and path in a variable

I already set the path and filename in a variable.
How to close the workbook using the filename that i already set?
This is the code:
Sub CLOSE_WORKBOOK_RAW()
Dim x As String
x = Left(ThisWorkbook.Name, (InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1))
Dim Filepath As String
Filepath = ThisWorkbook.Path
Dim Filename As String
Filename = Filepath & "\" & x & ".xlsx"
Dim Filename2 As String
Filename2 = Filepath & "\" & x & ".xlsm"
Workbooks(Filename).Close Savechanges:=True
End Sub
The short of your code appears to be embraced in
ThisWorkbook.Close Savechanges:=True
All the rest of it just confuses the issue. However, here is the syntax for constructing a file name if, for example, you want to save the active workbook, usually while it is other than ThisWorkbook.
Sub Close_Workbook_Raw()
Dim Filepath As String ' the path to save at
Dim Filename As String ' the file's name
Dim Ext As String ' the file name extension
Filepath = ThisWorkbook.Path ' or any other valid path
Filename = Format(Date, "yymmdd ") & "MyFile's name"
Ext = "xlsm"
With ActiveWorkbook
.SaveAs Filepath & "\" & Filename & "." & Ext
.Close
End With
End Sub
How to close the workbook using the filename that I already set?
It depends
Is the workbook already saved once?
Is it a newly created workbook?
Also what is the format (xlsx/xlsm) you are going to use.
See this example for saving as Xlsx
Dim x As String
x = Left(ThisWorkbook.Name, (InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1))
Dim Filepath As String
Filepath = ThisWorkbook.Path
Dim sFilename As String
sFilename = Filepath & "\" & x & ".xlsx"
Dim wb As Workbook
'~~> If already saved once
Set wb = Workbooks(x & ".xlsx")
'~~> If newly created and has the name `x`
Set wb = Workbooks(x)
wb.SaveAs Filename:=sFilename, FileFormat:=xlOpenXMLWorkbook
wb.Close (False)
Note:
Filename2 = Filepath & "" & x & ".xlsm"
When using saving it as .xlsm you have to be very careful as you are going to use the original file name; basically trying to overwrite the same file.

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

Error Object variable or With block variable not set only when Protected view activ

I am trying to get the following done. When I open workbook in folder, it opens, runs code where new copy of this workbook is created in "TEMP" folder and the original is closed. The idea is to have multiple copies open at the same time and on closing, all user updates copy into the original.
Everything works well when when workbook is opened second time, however on first opening when in Protected view I get Run-time error '91' Object variable or With block variable not set.
I have read a good bit about this issue but can't seem to figure it out.
Any help is much appreciated.
Private Sub Workbook_Open()
Dim strFilename, strDirname, strDirname2, strPathname, strDefpath As String
'Count files in folder
Dim MyFolder As String
Dim MyFile As String
Dim j As Integer
Dim strDefpatheee As String
Dim strDirnameeee As String
strDirnameeee = "TEMP"
strDefpatheee = Application.ActiveWorkbook.Path
MyFolder = strDefpatheee & "\" & strDirnameeee
MyFile = Dir(MyFolder & "\" & "*.xlsm")
Do While MyFile <> ""
j = j + 1
MyFile = Dir
Loop
'Save as same name + count of files in folder TEMP
On Error Resume Next ' If directory exist goto next line
strDirname = "TEMP" ' New directory name
strFilename = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5) & " " & j + 1 'New file name
strDefpath = Application.ActiveWorkbook.Path 'Default path name
'If IsEmpty(strDirname) Then Exit Sub
'If IsEmpty(strFilename) Then Exit Sub
'MkDir strDefpath & "\" & strDirname
strPathname = strDefpath & "\" & strDirname & "\" & strFilename 'create total string
ActiveWorkbook.SaveAs Filename:=strPathname & ".xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
Sheets("ACTIONS").Range("BG2").ClearContents
Sheets("ACTIONS").Range("D6").Select
PasswordEntry.Show
End Sub

Resources