简体   繁体   中英

How to avoid accdb row size limitation when using DoCmd.TransferSpreadsheet?

I'm using a DoCmd.TransferSpreadsheet to import data from Excel to Access. Everything works fine except some Excel rows that are truncated because there are too much bytes for an Access single row (not field).

I noticed that every field in Access is created as a text(255) while my Excel rows are all no more than 100 characters.

I think that if I manage to import my Excel files creating fields with a default length of 100 chars, I will no longer get truncated data.

Is there a way to set the default text length for Access fields to a specific number?


UPDATE

Decreasing the default field text size in Access 2010 options seems to be ignored when running DoCmd.TransferSpreadsheet

若要设置 Access (2007) 的默认文本长度,请单击 Office 按钮 >“Access 选项按钮”>“对象设计器”(在左侧窗格中),然后在“表格设计”下的“默认文本字段大小”框中输入 50并单击确定。

I wrote my own import function, and it works:

' Import from an Excel with a default field length different from 255 (must be < 255)
Function importFromExcel(fileName As String, fieldLength as integer)
    Dim my_xl_app As Object
    Dim my_xl_worksheet As Object
    Dim my_xl_workbook As Object
    Set my_xl_app = CreateObject("Excel.Application")
    Set my_xl_workbook = my_xl_app.Workbooks.Open(fileName)
    Set s = my_xl_workbook.Worksheets(1)

    Dim fieldsNumber As Integer
    Dim recordNumber As Long
    fieldsNumber = s.cells(1, s.Columns.Count).End(1).Column
    recordNumber = s.cells(s.Rows.Count, 1).End(3).Row
    tablename = "[" & Replace(GetFilenameFromPath(fileName), ".", "_") & "]"
    On Error Resume Next
    DoCmd.RunSQL "DROP TABLE " & tablename
    On Error GoTo 0

    ' Creo tabella
    sql = "CREATE TABLE " & tablename & " (F1 TEXT(" & fieldLength & ")) "
    DoCmd.RunSQL sql

    For i = 2 To fieldsNumber
        sql = "ALTER TABLE " & tablename & " ADD COLUMN F" & i & " TEXT(" & fieldLength & ")"
        DoCmd.RunSQL sql
    Next



    ' Ora insert
    For i = 1 To recordNumber
        sql = "INSERT INTO " & tablename & " VALUES ("
        For j = 1 To fieldsNumber
            sql = sql & " '" & Replace(s.cells(i, j), "'", "''") & "',"
        Next
        sql = Mid(sql, 1, Len(sql) - 1)
        sql = sql & ")"

    Next

    my_xl_workbook.Close SaveChanges:=False
    Set my_xl_app = Nothing
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM