我有一个Visual Basic应用程序,在其中打开Excel电子表格,处理数据,然后退出该应用程序。由于此应用程序将以计划的任务启动,并且如果不想创建新的电子表格,我也不想处理电子表格,因此我想在处理后将文件名从filename.xls更改为filename.xxx。然后,如果下次应用程序运行时filename.xls不存在,则不会进行任何处理。这是我正在执行的代码:
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()
执行代码时,尝试重命名文件时将执行Catch
。我收到此错误消息
该进程无法访问该文件,因为该文件正在被另一个进程使用。
我的印象是xl.App.Quit()
将关闭文件,但我想不会。
如何关闭文件以便重命名?