使用VBA和DAO将备忘录从Excel 2010传输到Access 2010

时间:2015-07-02 16:48:52

标签: excel vba excel-vba dao

我尝试将文本从Excel 2010传输到Access 2010.由于普通文本限制为256个字符,我想使用备忘录。现在,经过几个小时的搜索,我仍无法解决我的问题。

更具体一点: 此代码读取数据(在本例中为文本)并将其写入Access数据库。由于文本的限制,我需要在Access数据库中使用备注字段,但在调整完所有内容后,我无法找到此语句的数据类型(sSQL)。

我想要做的是更改以下代码:(稍微减少到相关位)

Sub Tester2()

    Dim wbName As String, shtSrc As Worksheet, shtDest As Worksheet

    wbName = GetRfqWbName("RFQ_")
    If Len(wbName) = 0 Then
        MsgBox "Didn't find the RFQ workbook!"
        Exit Sub
    Else
        'for example: you can substitute the sheet names instead
        Set shtSrc = Workbooks(wbName).Sheets(1)
        Set shtDest = Workbooks("Transfer Template.xlsm").Sheets(1)
    End If

    shtSrc.Range("J51").Copy shtDest.Range("B1")
    shtSrc.Range("D27").Copy shtDest.Range("B2")
    shtSrc.Range("D5").Copy shtDest.Range("B3")

End Sub

我正在考虑更换" Text"用"备忘录"但它没有工作。我也试过" LongText"和"字符串"。

1 个答案:

答案 0 :(得分:0)

我假设您要附加数据IT_Ticker的表已经存在。您并未具体说明您使用的Parameters,但下面的代码运行正常。

Option Explicit

Sub test()
    Dim ws As DAO.Workspace
    Dim db As DAO.Database
    Dim sDb As String
    Dim sSQL As String
    Dim qdf As QueryDef
    Dim userName As String
    Dim longText As String

    sDb = ActiveWorkbook.Path & "\DataBase2.accdb"

    Set ws = DBEngine.Workspaces(0)
    Set db = ws.OpenDatabase(sDb)

    'sSQL = "Parameters" _
    '& " SomeText Text; " _                       <<== Here << ==
    '& "INSERT INTO IT_Ticker (SomeText)" _
    '& " Values ([ SomeText ])"

    userName = Cells(2, 2).Value
    longText = Cells(3, 2).Value

    sSQL = "INSERT INTO IT_Ticker (UserName, ReallyLongText) Values (""" & _
           userName & """,""" & longText & """)"

    Set qdf = db.CreateQueryDef("", sSQL)

    'qdf.Parameters!SomeText = Worksheets("SomeSheet").Range("A1")

    qdf.Execute dbFailOnError
    Debug.Print qdf.RecordsAffected

    qdf.Close
    db.Close
    ws.Close

    Set qdf = Nothing
    Set db = Nothing
    Set ws = Nothing
End Sub