VBA 打开工作簿错误?
Posted
技术标签:
【中文标题】VBA 打开工作簿错误?【英文标题】:VBA Open workbook error? 【发布时间】:2017-03-06 09:04:04 【问题描述】:我正在使用 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)
【问题讨论】:
你试过我的代码了吗? 您在第一次调用 open 时提供了Password:="samples"
,但在第二次调用时未提供。
【参考方案1】:
只是为了检查,尝试将文件放在没有任何特殊字符的目录中。
即:C:\workbooks
确保打开文件的权限。
【讨论】:
【参考方案2】:你可以测试它是否已经打开:
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
【讨论】:
【参考方案3】:试试这个:
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)
【讨论】:
以上是关于VBA 打开工作簿错误?的主要内容,如果未能解决你的问题,请参考以下文章