将Excel表作为DAO记录集打开以进行追加

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

我正在尝试从DAO更新Excel文件中的表,就好像它是数据库表一样。听起来应该是可以的,但我找不到有关使用DAO打开Excel的任何文档。

我尽最大可能打开文件并获得记录集句柄,但看到错误3027“无法更新。数据库或对象是只读的。”当我尝试添加到记录集时。问题的一部分是我可以将工作表视为tabledef,但找不到该工作表中的excel表作为对象。也许我不知道将表作为记录集打开的正确语法。

我正在使用的代码指定dbOpenDynaset,就像使Access表可写一样。我正在尝试的可能吗?

错误发生在“ .AddNew”上:

Const dbOpenDynaset As Long = 2
Const dbAppendOnly As Long = 8
Const dbOptimistic As Long = 3

Public Sub OpenExcelAsDB(ByVal excelFile As String) 
    Dim fileExtension As String
    fileExtension = Right$(excelFile, Len(excelFile) - InStrRev(excelFile, "."))

    Dim connectionString As String
    Select Case fileExtension
    Case "xls"
        connectionString = "Excel 8.0;HDR=YES;IMEX=1"
    Case "xlsx"
        connectionString = "Excel 12.0 Xml;HDR=YES;IMEX=1"
    Case "xlsb"
        connectionString = "Excel 12.0;HDR=YES;IMEX=1"
    Case "xlsm"
        connectionString = "Excel 12.0 Macro;HDR=YES;IMEX=1"
    Case Else
        connectionString = "Excel 8.0;HDR=Yes;IMEX=1"
    End Select

    With CreateObject("DAO.DBEngine.120")
        With .OpenDatabase(excelFile, False, False, connectionString)
            With .OpenRecordset("LogSheet$", dbOpenDynaset, dbAppendOnly, dbOptimistic) 
                .AddNew
                With .Fields()
                    .Item("errorNumber").Value = errorNumber
                    .Item("errorDescription").Value = errorDescription
                    .Item("customNote").Value = customNote
                    .Item("errorDate").Value = Now()
                    .Item("Username").Value = UserLogon
                    .Item("Computer").Value = ComputerName
                End With

                .Update
                .Close
            End With

            .Close
        End With
    End With
End Sub
excel vba dao
1个回答
0
投票

在此时,这似乎是一个非常古老的技术堆栈。我认为这是在1990年代初期,而且肯定还会持续,但是支持似乎正在减少。因此,有了这个警告,您可以尝试这样的操作。

Sub DAOFromExcelToAccess()
' exports data from the active worksheet to a table in an Access database
' this procedure must be edited before use
Dim db As Database, rs As Recordset, r As Long
    Set db = OpenDatabase("C:\FolderName\DataBaseName.mdb") 
    ' open the database
    Set rs = db.OpenRecordset("TableName", dbOpenTable) 
    ' get all records in a table
    r = 3 ' the start row in the worksheet
    Do While Len(Range("A" & r).Formula) > 0 
    ' repeat until first empty cell in column A
        With rs
            .AddNew ' create a new record
            ' add values to each field in the record
            .Fields("FieldName1") = Range("A" & r).Value
            .Fields("FieldName2") = Range("B" & r).Value
            .Fields("FieldNameN") = Range("C" & r).Value
            ' add more fields if necessary...
            .Update ' stores the new record
        End With
        r = r + 1 ' next row
    Loop
    rs.Close
    Set rs = Nothing
    db.Close
    Set db = Nothing
End Sub

就个人而言,我会避免这类事情,并专注于某种云技术堆栈。

© www.soinside.com 2019 - 2024. All rights reserved.