I am a begginer with vbscript and I need to do one but It's not working. I need to create a Vbs that creates files for every row of a .csv file, but that new files have to have the name of the first colunm.
The csv below for example. I need to create a file with each rows content but the name of the new files have to be the name of each first colunm, "File1.txt"..."File4.txt"..."File3.docx".
File1.txt Whatever0
File4.txt Whatever4
File3.docx Whatever3
File7.csv Whatever9
File.xsl Whatever1
This is the .vbs I have up to now
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim destinationFolderName
destinationFolderName = "C:\Vbs_Files\OUT"
Set destinationFolder = objFSO.GetFolder(destinationFolderName)
Dim originalFolderName
originalFolderName = "C:\Vbs_Files\Excel"
Set originalFolder = objFSO.GetFolder(originalFolderName)
Do Until objInput.AtEndOfStream
line = objInput.ReadLine
IF line <> "" Then
Set objFile = objFSO.CreateTextFile(destinationFolder & colunm(0))
Set objFile = objFSO.CreateTextFile("C:\Vbs_Files\Temp" & colunm(1))
FileSystemObject.CopyFile "C:\Vbs_Files\Temp", "C:\Vbs_Files\OUT"
End if
Loop
Could you help me with this?
Related
I have a folder 1 where there are two CSV files present with name "Head.csv" & "Col.csv". I want to rename all those CSV files that are present in folder 1. The suffix that I wanted to add to each CSV file is another filename that exists in the folder2.
Filename 1 = Actual CSV File that I want to rename
Filename 2 = wanted to add this filename as Suffix. This file is present in the other folder.
Output of Filename: Filename1 + _ + FileName2 + .csv
Take for example in folder 1 "Head.csv" & "Col.csv" exist while in folder 2, the file exist with name general.txt. The filename in folder 2 can be any name.
Ex:- Head_general.csv
Option Explicit
Dim ofso, ofolder1,ofolder2,objFile, folderName1,folderName2
Dim File,sNewFile,a
folderName1 = "C:\Users\ShantanuGupta\Desktop\DRUM\Folder1" ' .csv file
folderName2 = "C:\Users\ShantanuGupta\Desktop\DRUM\Folder2" ' .txt file with different filename
Set ofso = CreateObject("Scripting.FileSystemObject")
Set ofolder1 = ofso.GetFolder(folderName1)
Set ofolder2 = ofso.GetFolder(folderName2)
Set objFile = oFolder2.Files
filesuffix = ofso.GetBaseName(oFolder2.Files)
For Each File In oFolder1.Files
sNewFile = File.Name
If instr(sNewfile, "Head.csv") > 0 THEN
File.Name = Replace(File.Name, "Head.csv", "Head_" & filesuffix & ".csv")
End If
If instr(sNewfile, "Col.csv") > 0 THEN
File.Name = Replace(File.Name, "Col.csv", "Col_" & filesuffix & ".csv")
End If
Next
Error Coming with Type Mismatch 'GetBaseName'.
Any help???
Files attached Here
This might work, although I'm not entirely sure how many files will be in 'folder2' but you get the idea:
Option Explicit
Dim objFile, sNewFile, filesuffix
Dim folderName1 : folderName1 = "C:\Users\ShantanuGupta\Desktop\DRUM\Folder1"
Dim folderName2 : folderName2 = "C:\Users\ShantanuGupta\Desktop\DRUM\Folder2"
Dim ofso : Set ofso = CreateObject("Scripting.FileSystemObject")
Dim ofolder1 : Set ofolder1 = ofso.GetFolder(folderName1)
Dim ofolder2 : Set ofolder2 = ofso.GetFolder(folderName2)
For Each objFile in ofolder2.Files
filesuffix = ofso.GetBaseName(objFile)
Next
For Each objFile In oFolder1.Files
sNewFile = ofso.GetBaseName(objFile.Name)
If StrComp(sNewfile,"Head",1) = 0 THEN
objFile.Name = Replace(sNewFile, sNewFile, sNewFile & "_" & filesuffix & ".csv")
End If
If StrComp(sNewfile,"Col",1) = 0 THEN
objFile.Name = Replace(sNewFile, sNewFile, sNewFile & "_" & filesuffix & ".csv")
End If
Next
Set ofolder1 = Nothing
Set ofolder2 = Nothing
Set ofso = Nothing
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.
When I want to convert a xlsx file into a csv with the following code:
WorkingDir = "C:\Users\Admin\Documents\example.xlsx"
Dim fso, FileName, SaveName, myFile
Dim objExcel, objWorkbook
Set fso = CreateObject("Scripting.FilesystemObject")
Set myFile = fso.GetFile(WorkingDir)
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.DisplayAlerts = True
FileName = Left(myFile, InStrRev(myFile, "."))
Set objWorkbook = objExcel.Workbooks.Open(myFile)
objWorkbook.Sheets(1).Range("A2:C2").Select
SaveName = FileName & "csv"
objWorkbook.SaveAs SaveName, 23
objWorkbook.Close
Set objWorkbook = Nothing
Set objExcel = Nothing
Set fso = Nothing
Set myFolder = Nothing
It works but asks me if i want to save my changes in the example.csv file. The saving should work without confirming and also should overwrite an eventually existing .csv file.
The second problem is that the range command where i select a specific part (rows and coumns) of the example.xlsx file which will be converted into a .csv file doesnt work. But there is no error. It seems that the vbscript jumps over this command.
Thank you in advance.
Try telling Excel that the file is already saved
objWorkbook.Saved = true
objWorkbook.Close
In terms of saving your select range, you could try
objWorkbook.Sheets(1).Range("A2:C2").Copy
dim sheet: set sheet = objWorkbook.Sheets.Add()
' Add()ing should actually activate the sheet
' sheet.Activate
sheet.Paste
' SaveAs will save the active sheet
objWorkbook.SaveAs FileName, 23
In otherwords, you need to duplicate the data in a second worksheet then save that worksheet as your csv. Closing the workbook (xlsx) without saving it will discard that new sheet.
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 an client the writes a file with data every 15 min. The name of the file is the date of that day.
So in the folder I can have for example:
2015-06-01.csv
2015-06-02.csv
2015-06-03.csv
What I want is that is to run a script every 15 minutes or if it’s possible to loop the script to see file changes.
I have been looking around an found one script that might work. But don’t get the copy file to work.
I only want to copy the file that’s been change last.
Option Explicit
Dim fso, path, file, recentDate, recentFile, filePath
Set fso = CreateObject("Scripting.FileSystemObject")
Set recentFile = Nothing
For Each file in fso.GetFolder("C:\CSV\Test\CSVOriginal").Files
If (recentFile is Nothing) Then
Set recentFile = file
ElseIf (file.DateLastModified > recentFile.DateLastModified) Then
Set recentFile = file
End If
Next
If recentFile is Nothing Then
WScript.Echo "no recent files"
Else
WScript.Echo "Recent file is " & recentFile.Name & " " & recentFile.DateLastModified
filePath = fso.GetFile(recentFile.Name)
WScript.Echo "Recent file is " & filepath
fso.CopyFile "C:\CSV\Test\CSVOriginal" +recentFile.Name,"C:\CSV\Test\CSVFlytt\"
End If
Here's one way. Loop through your folder to find the most-recently-modified file:
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objFile, strNewestFile, dtmMax
For Each objFile In objFSO.GetFolder("C:\CSV\Test\CSVOriginal").Files
If objFile.DateLastModified > dtmMax Then
dtmMax = objFile.DateLastModified
strNewestFile = objFile.Path
End If
Next
objFSO.GetFile(strNewestFile).Copy "C:\CSV\Test\CSVFlytt\"