检查excel文件是否打开,如果是关闭文件,如果没有转换csv文件excel Visual Basic

时间:2015-06-16 06:21:05

标签: excel vba excel-vba

我在创建条件时遇到了问题。请参阅下面的伪代码。提前谢谢

检查文件A.xls是否已打开     如果文件A.xls是打开的

    Close File A.xls
Else

    Convert File A.csv to .xls

End If

将文件A.csv转换为.xls

Dim DeleteEntries As Workbook
Dim WorksheetDeleteEntries As Worksheet
Dim WbOpen As Boolean

'Convert Acc_FR044_SAP.csv to excel
strDir = "C:\FR044 Automated Checker\"
strFile = Dir(strDir & "Acc_FR044_SAP.csv")

If Workbooks("Acc_FR044_SAP.xls") Is Nothing Then ' IM HAVING AN SUBSCRIPT ERROR IN THIS LINE

    WbOpen = False

Else
    Workbooks("Acc_FR044_SAP.xls").Close SaveChanges:=False

End If


Application.DisplayAlerts = False
Do While strFile <> ""
Set wb = Workbooks.Open(Filename:=strDir & strFile, Local:=True)
wb.SaveAs Replace(wb.FullName, ".csv", ".xls"), FileFormat:=xlExcel8
wb.Close True

Set wb = Nothing
strFile = Dir
Loop

2 个答案:

答案 0 :(得分:3)

这样可以检查文件是否在任何实例中打开,在任何机器上

Sub Sample()
    Dim bFileOpen As Boolean
    bFileOpen = IsWorkBookOpen("C:\yourfilename.xlsx")

    If bFileOpen Then
        MsgBox "File is open"
    Else
        MsgBox "File is Closed"
    End If
End Sub
来自Microsoft示例here

测试功能

Function IsWorkBookOpen(FileName As String)
    Dim ff As Long
    Dim ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
        Case 0
    IsWorkBookOpen = False
        Case 70
    IsWorkBookOpen = True
    Case Else
    End Select
End Function

答案 1 :(得分:1)

尝试使用适用于当前Excel实例的解决方案:

On Error Resume Next
Dim tmpWB As Workbook
Set tmpWB = Workbooks("Acc_FR044_SAP.xls")
On Error GoTo 0

If tmpWB Is Nothing Then 

    WbOpen = False

Else
    tmpWB .Close SaveChanges:=False

End If