导入Excel文件以使用宏访问

时间:2014-07-16 15:30:41

标签: vba ms-access access-vba

我需要将几百个excel文件导入一个访问表。我在网上找到了这个代码,但似乎没有用。我把它放在一个新模块中,单击运行,没有任何反应。

有什么建议吗?

Function DoImport()

Dim strPathFile As String, strFile As String, strPath As String
 Dim strTable As String
 Dim blnHasFieldNames As Boolean

 ' Change this next line to True if the first row in EXCEL worksheet
 ' has field names
 blnHasFieldNames = True

 ' Replace C:\Documents\ with the real path to the folder that
 ' contains the EXCEL files
 strPath = "C:\Test\TEST\"

 ' Replace tablename with the real name of the table into which
 ' the data are to be imported
 strTable = "Table1"

 strFile = Dir(strPath & "*.xls")
 Do While Len(strFile) > 0
       strPathFile = strPath & strFile
       DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
              strTable, strPathFile, blnHasFieldNames

   ' Uncomment out the next code step if you want to delete the
 ' EXCEL file after it's been imported
 '       Kill strPathFile

   strFile = Dir()

循环

End Function

1 个答案:

答案 0 :(得分:0)

使用TransferSpreadheet时,电子表格必须与目标表具有相同的列和数据类型。

您可以将表格中的所有字段设置为文字,这样您就可以导入电子表格而不管数据类型如何,但如果列与表格不匹配,则可能会导致导入错误。

即使将数据导入为Text,您也必须使用SQL和UDF的某种组合来测试数据并将其转换回所需的数据类型。

这是我用来测试数据类型并将其转换为我需要的任何UDF:

Public Function ValidateField(FieldVal As Variant, dbFieldID As Variant) As Variant
    If IsError(FieldVal) Then
        Select Case dbFieldID
            Case dbText
                ValidateField = Null
            Case dbInteger
                ValidateField = 0
            Case dbLong
                ValidateField = 0
            Case dbDouble
                ValidateField = 0
            Case dbDate
                ValidateField = 0
            Case dbCurrency
                ValidateField = 0
            Case Else
                ValidateField = Null
        End Select
    Else
        Select Case dbFieldID
            Case dbText
                ValidateField = CStr(FieldVal)
            Case dbInteger
                ValidateField = CInt(FieldVal)
            Case dbLong
                ValidateField = CLng(FieldVal)
            Case dbDouble
                ValidateField = CDbl(FieldVal)
            Case dbDate
                ValidateField = CDate(FieldVal)
            Case dbCurrency
                ValidateField = CCur(FieldVal)
            Case Else
                ValidateField = CVar(FieldVal)
        End Select
    End If
End Function