[英]VBA Open workbook error?
我正在使用vba嘗試打開工作簿(如果尚未打開)。
我的問題有時是工作簿可以由另一個用戶打開,所以如果工作簿被鎖定,那么我想向用戶提供一個選項,以只讀方式打開工作簿。
碼:
'Open Planner
On Error Resume Next
Set WB = Workbooks("2017 Planner.xlsx")
On Error GoTo 0
If WB Is Nothing Then 'open workbook if not open
On Error GoTo Message4
Set WB = Workbooks.Open("G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\8. 2017\2017 Planner.xlsx", Password:="samples", WriteResPassword:="samples", UpdateLinks:=False)
Message4:
Dim answer2 As Integer
answer2 = MsgBox("Oooops!" & vbNewLine & vbNewLine & "We had trouble opening the planner with Read/Write access. We can open the file in Read-Only but this means the planner won't automatically be updated. Would you like to continue?", vbYesNo + vbQuestion, "Notice")
If answer2 = vbNo Then
Exit Sub
Else
Set WB = Workbooks.Open("G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\8. 2017\2017 Planner.xlsx", ReadOnly:=True, IgnoreReadOnlyRecommended:=True)
End If
End If
由於某種原因,我在此行收到錯誤1004:
Set WB = Workbooks.Open("G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\8. 2017\2017 Planner.xlsx", ReadOnly:=True, IgnoreReadOnlyRecommended:=True)
嘗試這個:
dim link as string
link= "G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\8. 2017\2017 Planner.xlsx"
Set wb = Workbooks.Open(Filename:=link, UpdateLinks:=False, ReadOnly:=True, IgnoreReadOnlyRecommended:=True)
只是為了檢查,請嘗試將文件放在沒有任何特殊字符的某個目錄中。
即:C:\\ workbooks
確保有關打開文件的權限。
您可以測試它是否已經打開:
Sub Test()
Dim sFilePath As String
Dim wrkBk As Workbook
sFilePath = "G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\8. 2017\2017 Planner.xlsx"
If WorkBookIsOpen(sFilePath) Then
Set wrkBk = Workbooks.Open(sFilePath, ReadOnly:=True)
Else
Set wrkBk = Workbooks.Open(sFilePath)
End If
End Sub
Public Function WorkBookIsOpen(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
WorkBookIsOpen = (Err.Number <> 0)
On Error GoTo 0
End Function
由於函數WorkBookIsOpen
返回一個布爾值,而ReadOnly
屬性期望一個布爾值,因此可以使用以下較短的過程:
Sub Test2()
Dim sFilePath As String
Dim wrkBk As Workbook
sFilePath = "G:\BUYING\Food Specials\2. Planning\1. Planning\1. Planner\8. 2017\2017 Planner.xlsx"
Set wrkBk = Workbooks.Open(sFilePath, ReadOnly:=WorkBookIsOpen(sFilePath))
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.