参考文献打开了Wokrbook&如果正在使用工作簿,则创建错误消息

时间:2015-07-20 10:46:39

标签: excel vba excel-vba error-handling

您好我有以下代码,我想引用工作簿,以便我可以从已打开的工作簿中复制和粘贴数据。但是我正在努力正确地引用工作簿。有人可以帮忙吗? :)

文件名是“Pics& Benefits upload file.xlsm”

    Workbooks.Open Filename:= _
    "U:\FBS\PROJECTS_TEAM\MI\Sean's Projects\PICS and Benefits\Pics & Benefits upload file.xlsm"

Dim PicsFile As String
PicsFile = "Pics & Benefits upload file.xlsm"

如果其他人当前在文件名“Pics& Benefits upload file.xlsm”中,我还希望出现错误消息。如果另一个用户在文件中,它将退出宏。 (我不太清楚该怎么做)

由于

2 个答案:

答案 0 :(得分:1)

除了允许您引用正确工作簿的Mielks答案之外 - 在同一行中您还可以将文件以只读方式打开。

此代码将告诉您文件是否已打开 - 返回TRUE或FALSE(如果文件不存在,它也将返回TRUE - 无论哪种方式,它都会说您是否可以对该文件名和位置执行任何操作)

Public Function FileIsOpen(FullFilePath As String) As Boolean

    Dim ff As Long

    On Error Resume Next

    ff = FreeFile()
    Open FullFilePath For Input Lock Read As #ff
    Close ff
    FileIsOpen = (Err.Number <> 0)

    On Error GoTo 0

End Function

Public Sub test()

    If FileIsOpen("S:\Bartrup-CookD\MyTestFile.xls") Then
        MsgBox "That file's open, or doesn't exist - do something else."
    End If

End Sub

答案 1 :(得分:0)

你可以这样做:

Dim wkb As Excel.Workbook
Set wkb = Workbooks.Open(Filename:= _
    "U:\FBS\PROJECTS_TEAM\MI\Sean's Projects\PICS and Benefits\Pics & Benefits upload file.xlsm")