VBA将Excel电子表格逐行导入Access

Spe*_*eed 3 excel ms-access vba excel-2010

我正在调试一些代码,需要找出
DoCmd.TransferSpreadsheet acImport, , ".....
失败的地方,所以我决定逐行"手动"导入它以查看它的位置.

我想这样的东西就是我要找的东西:

mySpreadSheet = ConnectTo(Spreadsheet.xlsx)
while(!mySpreadSheet.EOF)
   get(mySpreadSheet.nextLine)
   SQL("UPDATE MyTable with mySpreadSheet.nextLine")
Run Code Online (Sandbox Code Playgroud)

我试过谷歌搜索无济于事.任何帮助深表感谢!


附加信息:

  • 电子表格和Access表的列名相同.
  • 每种数据类型都是nvarchar(MAX)(或"Memo"作为Access调用它)
  • 该表是SQL Server 2008的链接表

Fin*_*ink 10

如果您有一个定义良好的数据表格布局(HansUp答案),ADO运行良好.如果在加载对象之前需要添加控件,可以挂钩到excel工作簿,然后提取您喜欢的任何数据.这实际上取决于您需要的控制水平.

Public Sub LoadExcelToAccess(xlPath As String)
'uses late binding to open excel workbook and open it line by line

'make reference to Microsoft Excel xx.x Object Model to use native functions, requires early binding however

    Dim xlApp As Object 'Excel.Application
    Dim xlWrk As Object 'Excel.Workbook
    Dim xlSheet As Object 'Excel.Worksheet
    Dim i As Long
    Dim sql As String

    Set xlApp = VBA.CreateObject("Excel.Application")

    'toggle visibility for debugging
    xlApp.Visible = False

    Set xlWrk = xlApp.Workbooks.Open(xlPath)
    Set xlSheet = xlWrk.Sheets("Sheet1") 'modify to your perticular sheet

    'depends on what your trying to do with the sheet
    For i = 1 To 10

        'quick and dirty:  best to load items into custom class collection, then do processing there
        sql = "Insert Into [Temp] (Col1) VALUES (" & xlSheet.Cells(i, 1).Value & ")"
        DoCmd.RunSQL sql
    Next i

    'make sure to dispose of objects
    xlWrk.Close
    xlApp.Quit

    Set xlSheet = Nothing
    Set xlWrk = Nothing
    Set xlApp = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)


Han*_*sUp 5

您可以创建与电子表格的ADO连接(请参阅Excel 2007的连接字符串),然后打开具有该连接的ADO记录集(请参阅StackOverflow:VBA中的ADODB记录集,例如,如果不是excel字段为空).

然后遍历记录集行,并使用行的值创建SQL INSERT语句.

strInsert = "INSERT INTO MyTable (first_field, second_field) VALUES ('" & -
    rs2.Field(0).Value & "', '" & rs2.Field(1).Value & "');"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailonerror
Run Code Online (Sandbox Code Playgroud)

该代码剪断假定first_field和second_field是文本数据类型.如果它们是数字,则丢失单引号.

我认为这大致与你提出的要求相同.但是,在使用代码之前,我会检查电子表格是否干净地导入到新的本机Access表中.(另外,检查新表上的数据类型和约束是否与链接的SQL Server表的数据类型和约束兼容.)如果可行,可以尝试从Management Studio直接将电子表格导入SQL Server,或者任何适当的工具.