I managed to get the following piece of code put together:
'Constants
Const xlOpenXMLWorkbook = 51 '(without macro's in 2007-2016, xlsx)
Const xlOpenXMLWorkbookMacroEnabled = 52 '(with or without macro's in 2007-2016, xlsm)
Const xlExcel12 = 50 '(Excel Binary Workbook in 2007-2016 with or without macro's, xlsb)
Const xlExcel8 =56 '(97-2003 format in Excel 2007-2016, xls)
' Extensions for old and new files
strExcel = "xlsx"
strCSV = "csv"
' Set up filesystem object for usage
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Get folder name to process off the command line, make sure it's valid
If (WScript.Arguments.Count > 0) Then
strFolder = WScript.Arguments(0)
If Not objFSO.FolderExists(strFolder) Then
WScript.StdErr.WriteLine "Specified folder does not exist."
WScript.Quit
End If
Else
WScript.StdErr.WriteLine "No folder name specified to process."
WScript.Quit
End If
' Access the folder to process
Set objFolder = objFSO.GetFolder(strFolder)
' Load Excel (hidden) for conversions
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = False
' Process all files
For Each objFile In objFolder.Files
' Get full path to file
strPath = objFile.Path
' Only convert CSV files
If LCase(objFSO.GetExtensionName(strPath)) = LCase(strCSV) Then
' Display to console each file being converted
WScript.Echo "Converting """ & strPath & """"
' Load CSV into Excel and save as native Excel file
Set objWorkbook = objExcel.Workbooks.Open(strPath, False, True)
objWorkbook.SaveAs Replace(strPath, strCSV, strExcel), xlOpenXMLWorkbook
objWorkbook.Close False
Set objWorkbook = Nothing
End If
Next
'Wrap up
objExcel.Quit
Set objExcel = Nothing
Set objFSO = Nothing
Unfortunately I have 3 issues:
I was instructed to run this in the following manner:
Copy the code above and saved it as csv.vbs
Go to CMD and type in
cscript csv.vbs "C:\Users\Eitel\Desktop\3rd Party\Work Folder"
This is the path where the CSV files are.
I would prefer to have a way of executing the code by clicking on/opening a VBScript.
I received this error:
Input Error: Can not find script file "C:\Users\Eitel\csv.vbs"
I went to "C:\Users\Eitel\csv.vbs" and pasted the csv.vbs file in this location. I ran the command again and this is what was displayed:
"C:\Users\Eitel\Desktop\3rd Party\Work Folder\TestFile.CSV"
C:\Users\Eitel\csv.vbs(44.9) Microsoft Excel: Cannot save as that name. Document was opened as read-only.
I have no clue what this means or why it happens?
I noticed that while most of the files are .csv extensions, some of the files extensions are displayed as .CSV and some are .csv. I am wondering if this will affect the way in which the script is executed?
Here is the solution I needed:
Link: https://www.experts-exchange.com/questions/29088597/Change-Multiple-csv-files-into-xlsx-files.html?notificationFollowed=205599875
'Constants
Const xlOpenXMLWorkbook = 51 '(without macro's in 2007-2016, xlsx)
Const xlOpenXMLWorkbookMacroEnabled = 52 '(with or without macro's in 2007-2016, xlsm)
Const xlExcel12 = 50 '(Excel Binary Workbook in 2007-2016 with or without macro's, xlsb)
Const xlExcel8 =56 '(97-2003 format in Excel 2007-2016, xls)
' Extensions for old and new files
strExcel = "xlsx"
strCSV = "csv"
strXLS = "xls"
' Set up filesystem object for usage
Set objFSO = CreateObject("Scripting.FileSystemObject")
strFolder = "B:\EE\EE29088597\Files"
' Access the folder to process
Set objFolder = objFSO.GetFolder(strFolder)
' Load Excel (hidden) for conversions
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = False
' Process all files
For Each objFile In objFolder.Files
' Get full path to file
strPath = objFile.Path
' Only convert CSV files
If LCase(objFSO.GetExtensionName(strPath)) = LCase(strCSV) Or LCase(objFSO.GetExtensionName(strPath)) = LCase(strXLS) Then
' Display to console each file being converted
Wscript.Echo "Converting """ & strPath & """"
' Load CSV into Excel and save as native Excel file
Set objWorkbook = objExcel.Workbooks.Open(strPath, False, True)
strNewPath = objFSO.GetParentFolderName(strPath) & "\" & objFSO.GetBaseName(strPath) & "." & strExcel
objWorkbook.SaveAs strNewPath, xlOpenXMLWorkbook
objWorkbook.Close False
Set objWorkbook = Nothing
End If
Next
'Wrap up
objExcel.Quit
Set objExcel = Nothing
Set objFSO = Nothing
This will scan the directory for any xls or csv file and convert them into xlsx files.
Starting with this as the code:
Const ForReading = 1
Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSourceFile = objFSO.OpenTextFile("Path\file.csv", ForReading)
Set objDestinationFile = objFSO.OpenTextFile("Path\Database.csv", ForAppending)
'Loop start files in dir
Do Until objSourceFile.AtEndOfStream
strLine = objSourceFile.ReadLine
arrFields = Split(strLine, ",")
If arrFields(0) <> """""" Then
strContents = strContents & arrFields(1) & ","
End If
Loop
strContents = strContents & vbCrLf
objSourceFile.Close
objDestinationFile.Write strContents
'Move source file to processed directory
'Loop end files in dir
objDestinationFile.Close
Which is fine for one file at a time, but I'm trying to append many files into the single file.
Appreciate any tips.
Thanks.
Edit: So this was a request that started with a single file which turned into having to migrate many files. The original CSV needed to have its format changed and then placed into another easier to use CSV.
The issue is that there many files and each source file has to be modified before placing it into the destination file. I am new to VB Scripting and I was trying to be concise with my text. Thanks.
I appreciate the help.
I have a folder containing 1650 HTML files that, due to local authorities, must be also printed in paper form.
I have tried with classic ctrl+A (even if I was trying on smaller quantities) and then I have looked for PRINT label in the right click menu, but there's any.
If I choose to print multiple jpg or pdf files, the PRINT voice appears.
How am I supposed to print multiple html files? A batch file? (I have no knowledge about how to).
I have also thought to convert html to pdf, but had no success with PDF Creator and PDF Architect.
Any of you with some experience to share?
I have wrtten some code mixing the one given by Tim and what I found on stackoverflow, but had no success.
Here it is:
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\Users\mainUser\Desktop\ft"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "html" Then
On Error Resume Next
Const OLECMDID_PRINT = 6
Const OLECMDEXECOPT_DONTPROMPTUSER = 2
Const PRINT_WAITFORCOMPLETION = 2
Dim objExplorer
Set objExplorer = CreateObject("InternetExplorer.Application")
objExplorer.Navigate objFolder.Path +"\"+ objFile.Name
objExplorer.Visible = 1
Do while objExplorer.ReadyState <> 4
WScript.Sleep 1000 'milliseconds
Loop
oIExplorer.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER
End If
Next
It just opens one html in internet explorer. I thought it would have open all the files, and already in PRINT "mode".
I think I am missing something.
See this thread for looping through files in a directory: How to do something to each file in a directory with a batch script
Then you can use the native PRINT command so your batch file could be as simple as this:
for /f "delims=|" %%f in ('dir /b c:\') do PRINT %%f
In light of the comments below:
Ahh. Then you will likely have to automate IE to print the page. Play with a VBScript along these lines:
Const OLECMDID_PRINT = 6
Const OLECMDEXECOPT_DONTPROMPTUSER = 2
Const PRINT_WAITFORCOMPLETION = 2
objStartFolder = "C:\Users\mainUser\Desktop\ft"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(objStartFolder)
Set objExplorer = CreateObject("InternetExplorer.Application")
Set oShell = CreateObject("Shell.Application")
For Each objFile In objFolder.Files
strFileName = objFile.Name
If objFSO.GetExtensionName(strFileName) = "html" Then
handle = objExplorer.Hwnd
objExplorer.Navigate objFolder.Path + "\" + objFile.Name
For Each Wnd In oShell.Windows
If handle = Wnd.Hwnd Then Set objExplorer = Wnd
Next
Do While objExplorer.Busy
WScript.Sleep 1000 'milliseconds
Loop
objExplorer.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER
End If
Next
Set oShell = Nothing
Set objFSO = Nothing
Set objFolder = Nothing
Set objExplorer = Nothing
3rd Update:
I fixed the code above. I apologize.Its been some time since I've worked with IE. Apparently IE treats each tab as a new instance of IE, and loading a document "creates" a new tab. As a result, we have to load the page and then find our IE window again so we can set it back to the variable.
First, some context. I have an excel spreadsheet with a module that, using a piece of javascript on the site, imports data from a text file generated by a website.
Set Datasheet = Worksheets("Datasheet")
...
Set qtQtrResults = Datasheet.QueryTables _
.Add(Connection:=URL, Destination:=Datasheet.Cells(1, 1))
With qtQtrResults
.WebFormatting = xlNone
.WebSelectionType = xlSpecifiedTables
.WebTables = "1,2"
.Refresh
The URL goes to "site.com/download.jsp?Login=abc&search=123" which, when accessed in a browser, creates a text file that downloads to the browser's default download directory.
My problem is that I need to replicate this functionality in Access, importing the data from this text file into an existing table.
Can anyone offer a solution (other than use excel)?
I just tested the following and it worked for me in Access 2010:
Option Compare Database
Option Explicit
Sub DownloadCsvFromWeb()
Dim httpReq As Object, stm As Object
Set stm = CreateObject("ADODB.Stream")
stm.Type = 2 ' adTypeText
stm.Open
Set httpReq = CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open _
"GET", _
"http://www.example.com/downloads/gord/test.csv", _
False
httpReq.Send
stm.WriteText httpReq.responseText
stm.SaveToFile _
"C:\Users\Gord\Desktop\test.csv", _
2 ' adSaveCreateOverWrite
stm.Close
Set stm = Nothing
Set httpReq = Nothing
End Sub
That saves the file to disk (on my desktop, in this case). The code could then go on to use DoCmd.TransferText to import the data into an Access table.
I have a VBScript code snippet which converts my xls and xlsx files into csv files. However, I want each cell to be separated by a semicolon rather than a comma. On my computer, the list separator is set to semicolon instead of comma so when I open up an excel window and do save as csv, it separates by semicolon. However, my VBScript produces a csv file separated by commas. I found the code snippet online as I do not really know VBScript (I'm mainly a Java Programmer) that well. How can I change the code snippet to separate the csv files by semicolon rather than by comma?
if WScript.Arguments.Count < 2 Then
WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.SaveAs WScript.Arguments.Item(1), 6
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
you can keep your original script, only need to give a parameter to indicate local setting must apply. This saves my CSV with a ; separator
if WScript.Arguments.Count < 2 Then
WScript.Echo "Error! Please specify the source path and the destination. Usage: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = FALSE 'to avoid prompts
Dim oBook, local
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
local = true
call oBook.SaveAs(WScript.Arguments.Item(1), 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, local) 'this changed
oBook.Close False
oExcel.Quit
WScript.Echo "Done"
The use of a comma in delimited text files finds its roots in the regional settings. While the comma is standard in the US, other countries such as Germany use the semicolon instead. You can change the List Separator value in the Regional and Language settings and then choose CSV (Comma delimited) (.csv) from Excel's Save As window. The resulting file will be delimited by whatever value is in the system settings. This script changes default List Separator setting. Then it opens the specified spreadsheet and resaves it. It reverts the system setting to its previous value before finishing.
It accepts two command line parameters. The first is the input spreadsheet; the second is the output filename for the exported file.
strDelimiter = ";"
strSystemDelimiter = "" ' This will be used to store the current sytem value
Const HKEY_CURRENT_USER = &H80000001
' Get the current List Separator (Regional Settings) from the registry
strKeyPath = "Control Panel\International"
strValueName = "sList"
strComputer = "."
Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
objRegistry.GetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strSystemDelimiter
' Set it temporarily to our custom delimiter
objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strDelimiter
' Open spreadsheet with Excel and save it in a text delimited format
Const xlCSV = 6
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open(WScript.Arguments.Item(0))
objWorkbook.SaveAs WScript.Arguments.Item(1), xlCSV
objWorkbook.Close vbFalse ' Prevent duplicate Save dialog
objExcel.Quit
' Reset the system setting to its original value
objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strSystemDelimiter
After some testing, it seems that this only works through Excel's Save As dialog and not through command-line or automation. I've changed the script a little to make the Excel window visible and use shortcuts keys to open the Save As dialog through the Excel interface. This should do the trick. It worked for me on Vista x64 with Excel 2007. I hope this works for you.
strDelimiter = ";"
strSystemDelimiter = "" ' This will be used to store the current sytem value
Const HKEY_CURRENT_USER = &H80000001
' Get the current List Separator (Regional Settings) from the registry
strKeyPath = "Control Panel\International"
strValueName = "sList"
strComputer = "."
Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
objRegistry.GetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strSystemDelimiter
' Set it temporarily to our custom delimiter
objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strDelimiter
' Open spreadsheet with Excel and save it in a text delimited format
Const xlCSV = 6
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = vbTrue
Set objWorkbook = objExcel.Workbooks.Open(WScript.Arguments.Item(0))
WScript.Sleep 500 ' Delay to make sure the Excel workbook is open
strWorkbookName = objExcel.ActiveWorkbook.Name
strTitlebar = strWorkbookName
Set WshShell = CreateObject("WScript.Shell")
WshShell.AppActivate strTitlebar ' Make the workbook active so it receives the keystrokes
WshShell.SendKeys "%fa" ' Keyboard shortcuts for the Save As dialog
WScript.Sleep 500
WshShell.SendKeys "%tc{ENTER}" ' Change the Save As type to CSV
If WScript.Arguments.Count > 1 Then
WshShell.SendKeys "+{TAB}" & WScript.Arguments.Item(1)
WScript.Sleep 500
End If ' This If block changes the save name if one was provided
WshShell.SendKeys "{ENTER}" ' Save the file
WScript.Sleep 500
WshShell.SendKeys "{ENTER}" ' Dismiss the CSV warning dialog
Set WshShell = Nothing
objWorkbook.Close vbFalse ' Prevent duplicate Save dialog
objExcel.Quit
' Reset the system setting to its original value
objRegistry.SetStringValue HKEY_CURRENT_USER, strKeyPath, strValueName, strSystemDelimiter
The Function SaveAs is defined so :
.SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)
Thas is, to use the semicolon (if your regional language option are correctly set)
ExcelObj.Workbooks(1).SaveAs csvFile, 6,,,,,,,,,,True
You can reopen the file with the FSO object, then do a Replace() on the comma character.
Const OpenAsDefault = -2
Const FailIfNotExist = 0
Const ForReading = 1
Const ForWriting = 2
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set fCSVFile = _
oFSO.OpenTextFile("C:\path\file.csv", ForReading, FailIfNotExist, OpenAsDefault)
sFileContents = fCSVFile.ReadAll
fCSVFile.Close
sFileContents = Replace(sFileContents, ",",";"))
Set fCSVFile = oFSO.OpenTextFile("C:\path\file.csv", ForWriting, True)
fCSVFile.Write(sFileContents)
fCSVFile.Close
I changed the parameter to true, and worked for me.
if WScript.Arguments.Count < 2 Then
WScript.Echo "Erro! Especifique origem e destino. Exemplo: XlsToCsv SourcePath.xls Destination.csv"
Wscript.Quit
End If
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
call oBook.SaveAs(WScript.Arguments.Item(1), 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, true) --CHANGED
oBook.Close False
oExcel.Quit