Question

IN THE BOTTOM CODE THAT WORKED

Working on a variation of Convert XLS to CSV on command line that I could use to copy xls as csv.

I just want to copy files that are not yet copied, so need to check if file already exists in my target directory. Was thinking something like:

Set fso=CreateObject("Scripting.FileSystemObject")
Set sourcefldr=fso.getFolder(sourcepath)
Set targetfldr=fso.getFolder(targetpath)
for each sfile in sourcefldr.files
    for each tfile in target
    if not file in targetfldr.files then
    'create excelfile and save as csv

however file in targetfldr.files not working

How can I avoid looping over all my target files every time?

tks in advance!

EDIT:

Incorporated @Pankaj Jaju and @Ansgar Wiechers answer and below is working!

csv_format = 6
sourcestring ="C:\sourcefolder"
deststring= "V:\destfolder"

Set fso=CreateObject("Scripting.FileSystemObject")
Set sourcefldr=fso.getFolder(sourcestring)
Set destfldr=fso.getFolder(deststring)
Dim oExcel
Set oExcel = CreateObject("Excel.Application")
Dim oBook

for each sfile in sourcefldr.files
    destname = left(sfile.name,len(sfile.name)-3) & "csv"
    fulldest = fso.buildpath(destfldr, destname)
    if not fso.FileExists(fulldest) then
        Set oBook = oExcel.Workbooks.Open(sfile)
        oBook.SaveAs fulldest, csv_format
        oBook.Close False
        WScript.Echo "Copied " & fulldest
    end if
next

oExcel.Quit
Was it helpful?

Solution

Try this !

set fso=createobject("scripting.filesystemobject")
set sourcefldr=fso.getfolder(sourcepath).files

for each sfile in sourcefldr
    if not fso.fileexists(fso.buildpath(targetpath, sfile.name)) then
        fso.getfile(sfile).copy(fso.buildpath(targetpath, sfile.name))
    end if
next

OTHER TIPS

Best bet would be add all of your target folder files into a dictionary. This way you can just use "Exists" to search for it in the dictionary.

Set fso=CreateObject("Scripting.FileSystemObject")
Set filesDic = CreateObject("Scripting.Dictionary")
Set targetfldr=fso.getFolder(targetpath)

'add destination files into dictionary
For Each file in targetfldr.files
  filesDic.Add file.name, file.name
Next

This way all you need to do is check the new filename against the dictionary

filesDic.Exists(file.name)

This will just return a true / false

Here is a bit more information about the dictionary http://www.devguru.com/technologies/vbscript/13992

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top