I have a Visual Basic application where I open an Excel spreadsheet, process the data, and then exit the application. Since this application will be started with a scheduled task, and I don't want to process the spreadsheet if a new one has not been created, I want to change the file name from filename.xls to filename.xxx after processing. Then, if filename.xls is not present the next time the application runs, no processing will occur. This is the code I am executing:
Dim useXlsFile As String = "N"
Dim xlsFileName As String = "C:\VPA_FTP\ValuePoint\incoming\VW_OUT_PST_ACCURECORD_CREDS.xls"
Dim currdate As String = Now.Year
If Now.Month < 10 Then
currdate = currdate & "0" & Now.Month
Else
currdate = currdate & Now.Month
End If
If Now.Day < 10 Then
currdate = currdate & "0" & Now.Day
Else
currdate = currdate & Now.Day
End If
Dim renameXlsFileName = "VW_OUT_PST_ACCURECORD_CREDS" & currdate & ".xxx"
If My.Computer.FileSystem.FileExists(xlsFileName) Then
useXlsFile = "Y"
Else
MsgBox("File not found.")
End If
If useXlsFile = "Y" Then
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open(xlsFileName)
xlWorkSheet = xlWorkBook.ActiveSheet
Dim range As Excel.Range
range = xlWorkSheet.UsedRange
numberOfDataRecords = range.Rows.Count
numberOfColumns = range.Columns.Count
xlApp.DisplayAlerts = False
xlWorkBook.Saved = True
xlWorkBook.Close(True)
xlApp.Quit()
Try
My.Computer.FileSystem.RenameFile(xlsFileName, renameXlsFileName)
Catch ex As Exception
ReturnValue = ex.Message
Dim ReturnValuex As Exception
ReturnValuex = ex.InnerException
End Try
End If
Application.Exit()
When I execute the code, the Catch
is executed when trying to rename the file. I get this error message
The process cannot access the file because it is being used by another process.
I was under the impression that the xl.App.Quit()
would close the file but I guess not.
How can I close the file so I can rename it?