Link to home
Start Free TrialLog in
Avatar of davidam
davidamFlag for Canada

asked on

VBS to Convert csv file to excel file

Hello Experts,
We are using vbs to monitor a directory for incoming excel files and then perform certain operartions on those files.  We would like to change it to monitor for csv files and then, upon receiving a csv file, have vbs convert it to an excel file.  Attached is some of the code we now have.  How can we do this?
Dim xlApp				
Dim xlBook				
Dim FSO				
Set xlApp = CreateObject("Excel.Application")		
xlApp.Visible = False				
Set FSO = CreateObject("Scripting.FileSystemObject")	
Dim oBookToProcess				
strComputer = "."					
strDirToMonitor = "C:\servr\incoming"		
strProcDir = "C:\servr\calculate\"		
strTime = "20"					
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")				
Set colMonitoredEvents = objWMIService.ExecNotificationQuery _		
    ("SELECT * FROM __InstanceOperationEvent WITHIN " & strTime & " WHERE " _				
        & "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _				
            & "TargetInstance.GroupComponent= " _	
                & "'Win32_Directory.Name=" & Chr(34) & Replace(strDirToMonitor, "\", "\\\\") & Chr(34) & "'")	
On Error Resume Next				
Do				
	Err.Clear			
	Set objLatestEvent = colMonitoredEvents.NextEvent			
	If objLatestEvent.Path_.Class = "__InstanceCreationEvent" Then			
		For Each objFile In FSO.GetFolder(strDirToMonitor).Files		
			If Right(LCase(objFile.Name), 4) = ".xls" Then	
				FSO.MoveFile objFile.Path, strProcDir & "\"
				End If
			End If	
		Next		
		Call Next_Procedure		
	End If			
Loop

Open in new window

Avatar of leonstryker
leonstryker
Flag of United States of America image

The question is why? Just open the CSV file in Excel, and save it as an Excel file.
Avatar of davidam

ASKER

That is what I want to do...what changes do I have to make to accomplish this?
Avatar of duncanb7
duncanb7

You want convert Excel to CSV or CSV to EXCEL ?

convert Excel to CVS as follows
========================
ActiveWorkbook.SaveAs filename:=jspfilename, _
        FileFormat:=xlCSV, ReadOnlyRecommended:=False, CreateBackup:=False
You are already instancing Excel

Set xlApp = CreateObject("Excel.Application")      

So

Dim wkb As Object
Set wkb = xlApp.Workbooks.Open(myCVSfile)
wkb.SaveAs Filename:= myXLSfile, FileFormat :=xlOpenXMLWorkbook, CreateBackup:=False

Leon


Paste this in a notepad and save it as a vbs

Const xlnormal = -4143 
Const InputFile = "E:\Users\Siddharth Rout\Desktop\codes.Csv"
Const OutputFile = "E:\Users\Siddharth Rout\Desktop\MyFile.xls"

Dim oXL, wb1

Set oXL = CreateObject("Excel.Application")
Set wb1 = oXL.Workbooks.Open(InputFile)
wb1.SaveAs OutputFile, xlsnormal

wb1.Close SaveChanges = False
Set wb1 = Nothing
oXL.Quit
Set oXL = Nothing

Open in new window


Sid
xover

Sid
A small typo.

Please change line 9 in my code to

wb1.SaveAs OutputFile, xlnormal

Open in new window


Sid
Probably it is easy to solve
So, I leave here , bye bye
Avatar of davidam

ASKER

In terms of modifying my existing code I am thinking that I could change the .xls to .csv (in line 4)and then slip
Leon's line in there to just resave the file and then continue on with th rest of the code whcih is all looking for .xls files
Set objLatestEvent = colMonitoredEvents.NextEvent		
If objLatestEvent.Path_.Class = "__InstanceCreationEvent" Then	
	For Each objFile In FSO.GetFolder(strDirToMonitor).Files
		If Right(LCase(objFile.Name), 4) = ".xls" Then		Set wkb = xlApp.Workbooks.Open(myCVSfile)
  wkb.SaveAs Filename:= myXLSfile, FileFormat :=xlOpenXMLWorkbook, CreateBackup:=False
	         FSO.MoveFile objFile.Path, strProcDir & "\"	
		End If	
	    End If		
	Next			
    Call Next_Procedure

Open in new window

Avatar of davidam

ASKER

Please have a look at the attached code...it errors on the final line...expected statement at character 25
If Right(LCase(objFile.Name), 4) = ".cvs" Then
				If FSO.FileExists(strProcessingDir & "\" & objFile.Name) = True Then FSO.DeleteFile strProcessingDir & "\" & objFile.Name, True
				objLog.WriteLine Now & vbTab & "Moving " & objFile.Name & " to " & strProcessingDir & "\"
				Set wkb = xlApp.Workbooks.Open(objFile.Name)
				wkb.SaveAs Filename:=objFile.Name, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

Open in new window

Why it is xlOpenXMLWorkbook or not xlCSV if you want save it in csv format
Avatar of davidam

ASKER

I am trying to go from csv to excel...the following errors on the last line  'expected statement'

For Each objFile In FSO.GetFolder(strDirToMonitor).Files
   Dim strFileName
     If Right(LCase(objFile.Name), 4) = ".cvs" Then
     strFileName = Left(objFile.Name, Len(objFile.Name)-4)
     Set wkb = xlApp.Workbooks.Open(objFile)
wkb.SaveAs Filename:=strFileName, xlsnormal

Open in new window

Avatar of davidam

ASKER

I am trying everything I can think of on the syntax, but it always errors on the SaveAs line
Avatar of davidam

ASKER

I am thinking maybe the SaveAs needs a path?
Avatar of davidam

ASKER

Any ideas?
For Each objFile In FSO.GetFolder(strDirToMonitor).Files
   Dim strFileName
          If Right(LCase(objFile.Name), 4) = ".csv" Then
             strFileName = Left(objFile.Name, Len(objFile.Name)-4)
            Set wkb = xlApp.Workbooks.Open(objFile)
          wkb.SaveAs Filename:=strDirToMonitor & "\" & strFileName & ".xls", FileFormat:=xlsnormal, CreateBackup:=False

Open in new window

Try this:

wkb.SaveAs Filename:=strDirToMonitor & "\" & strFileName & ".xls"
Avatar of davidam

ASKER

Tried it , it will not load.  Char 21; Expected statement; 800A0400
Avatar of davidam

ASKER

Well, it loaded when I removed the Filename:= and just used SaveAs...
1-It is xlNormal not  xlsnormal
2- Did Check the file is open or not ? if not, using CheckFileAvailable() to check it

3-Try this  
====
For Each objFile In FSO.GetFolder(strDirToMonitor).Files
   Dim strFileName as string
          If Right(LCase(objFile.Name), 4) = ".csv" Then
             strFileName = Left(objFile.Name, Len(objFile.Name)-4)
            Application.Workbooks.Open filename:="objfile.Name ", ReadOnly:=False
Do Until ActiveWorkbook.Name = "objfile.Name"
Loop
ActiveWorkbook.SaveAs filename:= strDirToMonitor & "\" & strFileName & ".xls", _
        FileFormat:=xlNormal, ReadOnlyRecommended:=False, CreateBackup:=False

========

4-Please make sure all file name correct you can use debug.print and Msgbox to read & verfiy it once .

5-Supposed all ojbfile in the folder with ".xls" extentsion as you know
Be careful coding at  "For Each objFile In FSO.GetFolder(strDirToMonitor).Files" , the file in the folder
might not be with ".xls" extentsion.


Be sure and check  Ojbfile could be opened or not in Excel before do anything
 
Everyday , I use such FSO , open, saveas file for more than 200 files, but no any issue.
If you send your example file and VBA code to us that will be easier to speed up solution,



Be careful if you removed the Filename:=  even it works but not stable ,
if you do the code for many times and many files, you will see the error will happen in future that
I always experience a lot before.
Try to put it for safe, and solve the root cause out step by step, hurry is just final to wasting time.
Be careful if you removed the Filename:=  even it works but not stable

I originally forgot that this is being done in VBS, which means those param names can not be used. In VB or VBA they should be as it is much clearer and you do not have to relly on the order of the parameters, but it really has no effect on stability.
Anyway, glad to see you got the final solution.
Avatar of davidam

ASKER

Am I supposed to put the name of the file in place of objfile.Name in the following line?
    Application.Workbooks.Open filename:="objfile.Name ", ReadOnly:=False
You should be putting a path and a name there.
Avatar of davidam

ASKER

to leonstryker
When you say you do not use those parameters in vbs, are you referring only to the 'filename:=' or are you also referring to 'FileFormat:=xlNormal, ReadOnlyRecommended:=False, CreateBackup:=False' parameters?
Avatar of davidam

ASKER

Sorry, I was just trying to rekindle that earlier conversation...you can see that I referenced it and I was hoping that I could append it to the original...is that doable
Avatar of davidam

ASKER

Ok I see that I can still find all of the stuff I tried to post...
Here is the code converted into a full set of code. This code will load but it does not work.  I think  the problem lies in the fact that I need to have separate obects for the csv file and for the resulting xls file.  Also, for my application,  the resulting xls file needs to become  the same object as it would have been, if we were just passing through an xls file through. .

Dim xlApp
Dim objFSO
Dim oBookToProcess
Const xlUp = -4162
Const xlDown = -4121
Const xlValues = -4163
Set xlApp = CreateObject("Excel.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strComputer = "."

strDirToMonitor = "C:\srvr\filesin\"
strProcessingDir = "C:\srvr\Processing\"
 
"at this point code sets up the monitoring of C:\srvr\filesin\  for an __InstanceCreationEvent (a file is transferred in)"

Do
Err.Clear
Set objLog = objFSO.OpenTextFile(strLogFile, ForAppending, True)
Set objLatestEvent = colMonitoredEvents.NextEvent
    If objLatestEvent.Path_.Class = "__InstanceCreationEvent" Then
    "write to txt file"
        For Each objFile In objFSO.GetFolder(strDirToMonitor).Files
        xlApp.DisplayAlerts = False
            If Right(LCase(objFile.Name), 4) = ".csv" Then
            strFilename = Left(objFile.Name, Len(objFile.Name)-4)
               If objFSO.FileExists(strProcessingDir & "\" & objFile.Name) = True Then objFSO.DeleteFile strProcessingDir & "\" & objFile.Name, True
                 objLog.WriteLine Now & vbTab & "Moving " & objFile.Name & " to " & strProcessingDir & "\"
                Application.Workbooks.Open objFile.Name
          ActiveWorkbook.SaveAs strProcessingDir & "\" & strFilename & ".xls"  
          If Err.Number <> 0 Then
          "write to txt file"
          Err.Clear
          End If
     End If
Next
 "Call a procedure that is expecting an xls file in strProcessingDir"
End If
"close text file"
Loop

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of RobSampson
RobSampson
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the grade.

Regards,

Rob.
Sorry guys, I just had a chance to check this out on Excel 2003, and xlWorkbookNormal should have a value of -4143, not 56, and is also called xlNormal, so that can be changed if you want.

Regards,

Rob.