“运行时错误‘70’:权限被拒绝”在 MS Access 上运行备份代码时

问题描述 投票:0回答:1

我有一个访问表单,可以使用以下代码为我的项目(访问 2019)进行备份:

' Save the backup path to tblConfig
Private Sub SaveBackupPath()
    Dim db As DAO.Database
    Dim rs As DAO.Recordset

    Set db = CurrentDb
    Set rs = db.OpenRecordset("tblConfig", dbOpenDynaset)

    rs.FindFirst "SettingName = 'BackupPath'"
    If Not rs.NoMatch Then
        rs.Edit
        rs!SettingValue = Me.backupPath.Value
        rs.Update
    End If

    rs.Close
    Set rs = Nothing
    Set db = Nothing
End Sub

' Retrieve the backup path from tblConfig
Private Function GetBackupPath() As String
    Dim db As DAO.Database
    Dim rs As DAO.Recordset

    Set db = CurrentDb
    Set rs = db.OpenRecordset("tblConfig", dbOpenDynaset)

    rs.FindFirst "SettingName = 'BackupPath'"
    If Not rs.NoMatch Then
        GetBackupPath = rs!SettingValue
    Else
        ' Default path (e.g., USB pen drive)
        GetBackupPath = "C:\myapp\backup\Database_Backup.accdb"
    End If

    rs.Close
    Set rs = Nothing
    Set db = Nothing
End Function
Private Sub backupPathBtn_Click()
    Dim dlg As FileDialog
    Dim selectedPath As String

    Set dlg = Application.FileDialog(msoFileDialogFolderPicker)

    If dlg.Show = -1 Then
        selectedPath = dlg.SelectedItems(1)
        'gSelectedPath = selectedPath 
        Me.backupPath.Value = selectedPath
        MsgBox "" & selectedPath
    Else
        selectedPath = "C:\myapp\backup"
        'gSelectedPath = selectedPath 
        Me.backupPath.Value = selectedPath
        MsgBox " " & selectedPath
    End If
End Sub
Private Sub cmdBackup_Click()
    Dim sourcePath As String
    Dim backupPath As String

    ' Set the source path to the current database location
    sourcePath = CurrentDb.Name

    ' Get the backup path from tblConfig
    backupPath = GetBackupPath()

    ' Copy the file
    FileCopy sourcePath, backupPath

    MsgBox "Backup created successfully!"
End Sub
Private Sub cbtn_Click()
DoCmd.Close
End Sub

我尝试从我的电脑上的不同位置运行该程序并更改备份位置,但是当我运行命令按钮时,我得到了

Run-Time error '70': Permission denied
,我的代码有问题还是我弄乱了?

我尝试运行该程序来备份我的项目

vba ms-access runtime-error ms-office
1个回答
0
投票
FileCopy

如果文件当前打开,将抛出权限被拒绝错误。您可以做的是使用 FileSystemObject 来做到这一点。

Public Function FileCopy(sourceFileName As String, targetFilename As String)
    
    Dim fso As Object
    Set fso = VBA.CreateObject("Scripting.FileSystemObject")
    
    Call fso.CopyFile(sourceFileName, targetFilename, [overwrite]True)
    
    Set fso = Nothing
    
End Function
© www.soinside.com 2019 - 2024. All rights reserved.