TransferSpreadSheet给出错误3027“无法更新。数据库或对象是只读的。”

时间:2014-10-03 15:39:39

标签: ms-access access-vba ms-access-2003

我正在尝试导出动态SQL语句的结果,但不断收到错误3027“无法更新。数据库或对象是只读的。”。我正在使用Access 2003. GetYearFromDirName(sFolder)从目录结构中解析出一年,并将其用作SQL结果中的计算列。

以下是相关代码:

sSQL = "SELECT INDEXDB1.IFIELD1 AS TestArea, INDEXDB1.IFIELD2 AS TSID, INDEXDB1.IFIELD3 AS MapCoord, " _
    & "INDEXDB1.IFIELD4 AS Community, INDEXDB1.IFIELD5 AS Address, INDEXDB1.IFIELD6 AS DocNum, " _
    & "'" & GetYearFromDirName(sFolder) & "' AS Yr FROM INDEXDB1;"

'DoCmd.TransferSpreadsheet acExport, , sSQL, sFolder & "\" & BoxNum & ".csv"
'DoCmd.OutputTo acOutputQuery, "ExportRecs", acFormatXLS, sFolder & "\" & BoxNum & ".csv"

SaveToExcel sSQL, sFolder & "\" & BoxNum & ".csv"

呼叫:

Public Sub SaveToExcel(strSQL As String, strFullFileName As String)
Dim strQry As String
Dim db As Database
Dim Qdf As QueryDef

On Error GoTo SaveToExcel_err

strQry = "TempQueryName"

Set db = CurrentDb
'Set Qdf = db.CreateQueryDef(strQry, strSQL)

'DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, strQry, strFullFileName, True

'DoCmd.DeleteObject acQuery, strQry

With db
    ' Create permanent QueryDef.
    Set Qdf = .CreateQueryDef(strQry, strSQL)
    ' Open Recordset and print report.
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel3, strQry, strFullFileName, True
    ' Delete new QueryDef because this is a demonstration.
    .QueryDefs.Delete Qdf.Name
    .Close
End With


Exit Sub

SaveToExcel_err:
    MsgBox Error & " " & Err & " in sub SaveToExcel. Close program and start over."

End Sub

有没有更好的方法来导出动态SQL语句结果?最后,我需要一个CSV文件。

1 个答案:

答案 0 :(得分:1)

您可以在Excel中打开它,但CSV是文本格式,因此您需要使用DoCmd.TransferText而不是DoCmd.TransferSpreadsheet。使用“导出数据向导”手动完成导出一次。当您这样做时,您将使用魔杖来创建和命名导出规范。这将指定逗号作为分隔符,双引号指定为文本分隔符。您创建的导出规范的名称将作为第二个参数传递给TransferText