Avatar of Lukáš Stacke
Lukáš Stacke

asked on 

VBS automatically reopen Excel file

Hello Guys,
I have a script which opens all excel files in folder and run a macro in all of them. Unfortunately it keeps asking me that the excel file is already opened and if I would like to reopen it. I wanted to kill the process, but it doesn't really work as it should. Even when I manually kill the process and run the script it is asking me again, if i would like to reopen already open file. The problem with opening of excel occurs in  Sub ProcessExcelFile(sFileName).
Could you please advise what should be changed in bellow code? Thank you.

here is the code:

Const sRootFolder = "C:\test\"

Dim oFSO, oFile 
Dim xlApp, xlBook, objWorkbook 

 oShell.Run "taskkill /f /im EXCEL.EXE", , True

Sub Start()
     ProcessFilesInFolder sRootFolder
 End Sub

Sub ProcessFilesInFolder(sFolder)
     ' Process the files in this folder
     For Each oFile In oFSO.GetFolder(sFolder).Files
         If IsExcelFile(oFile) Then ProcessExcelFile oFile.Path
 End Sub

Sub Initialize()
     Set oFSO = CreateObject("Scripting.FileSystemObject")
     Set xlApp = CreateObject("Excel.Application")   
 End Sub

Sub Finish()
     Set xlBook = Nothing 
     Set xlApp = Nothing    
     Set oFSO = Nothing
 End Sub

Function IsExcelFile(oFile)
     IsExcelFile = (InStr(1, oFSO.GetExtensionName(oFile), "xls", vbTextCompare) > 0) And (Left(oFile.Name, 1) <> "~")
 End Function

Sub ProcessExcelFile(sFileName)   
     Set xlBook = xlApp.Workbooks.Open(sFileName, 0, True) 
     Set objWorkbook = xlApp.Workbooks.Open(sFileName)     
     xlApp.Run "import_test"
 End Sub 
 Sub Save()

oShell.Run "taskkill /f /im EXCEL.EXE", , True
  WScript.Echo "Finished."
 End Sub

Open in new window

VB ScriptMicrosoft ExcelMicrosoft Office

Avatar of undefined
Last Comment
Lukáš Stacke

8/22/2022 - Mon