【发布时间】:2018-03-12 12:02:42
【问题描述】:
我有一个场景可以在另一个工作簿路径中的工作簿中进行一些更改。但问题是我需要检查工作簿是否已经打开。如果不是,我需要将打开的实例添加到工作簿变量中。
这是我用来检查工作簿是否打开的代码,然后是打开代码
Function IsFileOpen(fileFullName As String)
Dim FileNumber As Integer
Dim errorNum As Integer
On Error Resume Next
FileNumber = FreeFile() ' Assign a free file number.
' Attempt to open the file and lock it.
Open fileFullName For Input Lock Read As #FileNumber
Close FileNumber ' Close the file.
errorNum = Err ' Assign the Error Number which occured
On Error GoTo 0 ' Turn error checking on.
' Now Check and see which error occurred and based
' on that you can decide whether file is already
' open
Select Case errorNum
' No error occurred so ErroNum is Zero (0)
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied." is 70
' File is already opened by another user.
Case 70
IsFileOpen = True
' For any other Error occurred
Case Else
Error errorNum
End Select
End Function
Public Function getConsolidatedDataFile() As Workbook
Dim p As String
p = ActiveWorkbook.Path
Dim cf As String
cf = printf("{0}\ConsolidatedData.xlsx", p)
Dim wb As Workbook
Dim fo As Boolean
fo = IsFileOpen(cf)
If fo = False Then wb = Workbooks.Open(filename:=cf)
''I need to get the code for this place of fo is true
getConsolidatedDataFile wb
End Function
因此,如果文件打开,我需要将该工作簿放入该 wb 变量中。
【问题讨论】:
-
您需要保留您打开的所有工作簿及其路径的参考,然后在使用
Application.ActiveWorkbook = TheWorkBook激活它之前比较打开它的路径 -
如果你喜欢一个例子我可以添加它
-
@Tarek.Eladly 当然我喜欢有一个..唯一的事情就是在已经打开的时候获取打开的工作簿的实例
-
什么是
printf?是自定义函数吗?你的代码编译了吗? -
@Vityata Yea.. 这是我的自定义函数,类似于 C# 或 VB.NET 中的 String.format