如何使用VBA“锁定文件以进行编辑”

时间:2013-12-29 05:10:19

标签: excel excel-vba vba

我正在编写一个很多人将在网络上使用的会计程序。程序从网络访问文件,任何用户都可以编辑这些文件。编辑的工作原理是将文件导入程序,允许用户进行更改,然后打开原始文件并用更改的数据替换旧数据。

问题是,如果两个人导入同一个文件并且都进行了更改,则保存更改的第二个人将覆盖第一个人的更改。

我意识到我可以让程序在编辑时在后台打开文件,这会将其锁定以供第二个用户编辑。我只是觉得文件被打开会被破坏。有没有办法让用户使用VBA锁定文件进行编辑而不实际打开文件。那就是我只会在我更换数据的那一刻打开它。

我认为我不是很清楚,但任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:1)

此代码:

<强>码

Option Explicit

Sub SetAttribue()
Dim strFile As String
strFile = "c:\temp\test.xlsx"
If Not IsWorkBookOpen(strFile) Then
      SetAttr strFile, vbReadOnly
      MsgBox "file now readonly"
    Else
        MsgBox "File is already open"
    End If
End Sub

检查子

Function IsWorkBookOpen(FileName As String) As Boolean
    Dim ff As Long
    Dim ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

答案 1 :(得分:-1)

这不能很好地工作,更好的选择是使用:

Function IsWorkBookOpen(FileName As String) As Boolean

    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 Binary Access Read Write Lock Read Write 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, 53, 52
            IsFileOpen = True

        ' Another error occurred.
        Case Else
            Error errnum
    End Select

End Function