以只读模式打开adodb与excel文件的连接

时间:2015-08-11 12:12:23

标签: excel vba connection adodb

案例:在Windows 7 64位上的Excel 2013中的VBA脚本中使用adodb.connection以只读方式打开Excel文件(.xlsx)。

问题:在adodb的连接字符串中依次将 Mode 参数设置为 Read ,似乎打开了excel文件进​​行编辑以只读模式打开连接:

szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                "Data Source=" & SourceFile & ";" & _
                "Mode=Read;" & _
                "Extended Properties=""Excel 12.0;HDR=Yes;"";"

测试:我打开连接后设置了一个断点,如下所示

Set rsCon = CreateObject("ADODB.Connection")
rsCon.Open szConnect

并测试源文件是否在'Mode = Read;'中打开通过adodb,它仍然可以被其他用户/连接以写入/编辑模式打开我尝试通过文件浏览器打开它,同时脚本处于中断模式但是警告说文件“被锁定以进行编辑“弹出,我被迫以只读模式打开。

那可能是什么错误?

这里我粘贴了下面评论中提到的整个代码,所以人们可能会运行代码来查找问题,这仍然是一个问题,想要以只读模式打开文件的原因是为了避免破坏源文件由于代码中的任何错误而让其他用户以写入模式打开文件来编辑文件:

Public Sub ADODBTEST()

    'the paths to a shared file in local network pcs
    Dim szSourceFile As String
    'you might want to comment/uncomment one of the following szSourceFile paths for testing purposes
    szSourceFile = "\\NetworkPC\READONLYACCESS\SourceFile.xlsx" 'A source file shared in a folder giving read-only access
    'szSourceFile = "\\NetworkPC\WRITEACCESS\SourceFile.xlsx" 'A source file shared in a folder giving write access

   'the connection string that sets the Mode=Read
    Dim szConnect As String
    szConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                "Data Source=" & szSourceFile & ";" & _
                "Mode=""Read"";" & _
                "Extended Properties=""Excel 12.0;HDR=No;"";"

    'creating the rsCon connection object
    Dim rsCon As Object
    Set rsCon = CreateObject("ADODB.Connection")
    'opening a connection to the SourceFile.xlsx through szConnect connection string
'***THE LINE WHERE ALL THE PROBLEMS HAPPEN: might be a good idea to set a breakpoint here
    rsCon.Open szConnect

'THE REST OF THE CODE IS MOSTLY FOR OUTPUT DEMONSTRATION
    'SQL code needed to read data from SourceFile.xlsx
    Dim szSQL As String
    szSQL = "SELECT * FROM A1:A1;"

    'creating rsData object
    Dim rsData As Object
    Set rsData = CreateObject("ADODB.Recordset")

    'opening and reading data according to szSQL and rsCon
    rsData.Open szSQL, rsCon, 0, 1, 1

    'Outputing some data for more clarification
    Dim szData As String
    szData = rsData.Fields(0).Value

    'in case the source file pops-up in foreground and is activated
    'if VBA does not reference ThisWorkbook.Worksheets(1) the read data
    'unwantedly is copied to the source file that is activated
    ThisWorkbook.Worksheets(1).Cells(1, 1).Value = "Connection String (Mode=Read): " & rsCon.ConnectionString
    ThisWorkbook.Worksheets(1).Cells(2, 1).Value = szData

    'cleaning the connection and data
    rsData.Close
    Set rsData = Nothing
    rsCon.Close
    Set rsCon = Nothing

End Sub

1 个答案:

答案 0 :(得分:1)

我不确定我是不是在说平庸的事情,而是为什么在代码运行时让用户有可能打开文件?我发现这个页面的原因是寻找一个问题的解决方案,文件被阻止在代码运行之后。解决方案非常简单 - 首先关闭,然后设置为空。

rsCon.Close

设置rsCon = Nothing