Excel VBA刷新文档打开为只读

是否有可能刷新打开为只读的文档,如果其他人有它打开写入它显示自上次刷新以来做的任何更新,但不偏离活动工作表?

我已经完成了前者,但是当它重新打开时,它会在最后一次保存之前打开任何工作表。

Sub refresh() Application.DisplayAlerts = False Workbooks.Open Filename:=ActiveWorkbook.Path & "\" & "name.xls", ReadOnly:=True End Sub 

谢谢

此代码进入两个工作簿

  1. 它使用SheetActivate事件来连续地写一个主文件(在上面的例子中是name.xls)的当前表的日志到一个log.txt文件
  2. “控制器”工作簿用于:
    • testing主文件是否打开,
    • 如果是,则打开一个只读版本(如果不是,则实际的文件被正常打开)
    • 可以访问文件日志(存储最后一个工作表,Windowslogin名和当前时间 – 也许矫枉过正)来设置最近的工作表。

注意:
1.我只能在我的本地机器上testing这个,在我的主文件上运行两个独立的Excel实例,因为Excel不会让相同的文件在同一个实例中打开两次)
2.而不是控制器工作簿我会build议使用从桌面快捷方式执行的VBScript

更改此行以设置要testing的文件path和名称是否处于打开状态
StrFileName = "c:\temp\main.xlsm"

Code for document to be opened: ThisWorkbook module

 Private Sub Workbook_SheetActivate(ByVal Sh As Object) Open ThisWorkbook.Path & "\log.txt" For Append As #1 Print #1, Sh.Name & ";" & Environ("username") & ":" & Format(Now(), "dd-mmm-yy hh:mm") Close #1 End Sub 

Code for Controller workbook: Normal module

我更新了微软网站代码来testingStrFileName是否已经打开。 如果它被打开,那么只读版本会打开到最新的页面

 Sub TestFileOpened() Dim Wb As Workbook Dim StrFileName As String Dim objFSO As Object Dim objTF As Object Dim strLogTxt As String Dim arrStr StrFileName = "c:\temp\main.xlsm" If Dir(StrFileName) = vbNullString Then MsgBox StrFileName & " does not exist", vbCritical Exit Sub End If If IsFileOpen(StrFileName) Then Set Wb = Workbooks.Open(StrFileName, , True) If Dir(Wb.Path & "\log.txt") <> vbNullString Then Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTF = objFSO.OpenTextFile(Wb.Path & "\log.txt", 1) Do Until objTF.AtEndOfStream strLogTxt = objTF.ReadLine Loop objTF.Close arrStr = Split(strLogTxt, ";") On Error Resume Next If Not IsEmpty(arrStr) Then Wb.Sheets(arrStr(0)).Activate If Err.Number <> 0 Then MsgBox arrStr(0) & " could not be activate" End If On Error GoTo 0 End If Else Set Wb = Workbooks.Open(StrFileName) End If End Sub ' This function checks to see if a file is open or not. If the file is ' already open, it returns True. If the file is not open, it returns ' False. Otherwise, a run-time error occurs because there is ' some other problem accessing the file. Function IsFileOpen(filename As String) Dim filenum As Integer, errnum As Integer On Error Resume Next ' Turn error checking off. filenum = FreeFile() ' Get a free file number. ' Attempt to open the file and lock it. Open filename For Input Lock Read As #filenum Close filenum ' Close the file. errnum = Err ' Save the error number that occurred. On Error GoTo 0 ' Turn error checking back on. ' Check to see which error occurred. Select Case errnum ' No error occurred. ' File is NOT already open by another user. Case 0 IsFileOpen = False ' Error number for "Permission Denied." ' File is already opened by another user. Case 70 IsFileOpen = True ' Another error occurred. Case Else Error errnum End Select End Function