|
本帖最后由 liangguoqiang 于 2014-8-13 13:39 编辑
最近学习ACCESS,在导入EXCEL数据时,出现字段F1不存在,无法导入的错误。本人是用VBA编写程序的,导入的EXCEL见附件:
本人想吧EXCEL中的A2:A5,B3:E5导入到ACCESS表中,同时A2与A5作为字段名称,自己写得代码如下:
Private Sub Command1_Click()
Dim fileNumber As Long
Dim File_Name As String
Dim i As Long
Dim j As Long
Dim m As Long
Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook
Set dOpen = Application.FileDialog(1)
With dOpen
.Filters.Clear
.Filters.Add "MML files", "*.xlsm,*.xlsx"
.Show
End With
If dOpen.SelectedItems.Count > 0 Then
MsgBox "你选择导入" & dOpen.SelectedItems.Count & "个数据文件"
For fileNumber = 1 To dOpen.SelectedItems.Count
File_Name = dOpen.SelectedItems(fileNumber)
Set xlBook = xlApp.Workbooks.Open(File_Name)
Text3.Value = "正在导入,请稍等。。。。"
For i = 1 To xlBook.Sheets.Count
sheetname = xlBook.Sheets(i).Name
If sheetname <> "高中" And sheetname <> "Index" Then
If sheetname = "ENBFunctionTDD" Then
j = xlBook.Application.CountA(xlBook.Sheets(i).Range("C:C"))
m = 12
y = Split(xlBook.Sheets(i).Cells(1, m).Address, "$")(1)
DoCmd.TransferSpreadsheet acImport, 8, sheetname, File_Name, True, sheetname & "!B1:" & y & "1"
DoCmd.TransferSpreadsheet acImport, 8, sheetname, File_Name, False, sheetname & "!B3:" & y & j
Else
j = xlBook.Application.CountA(xlBook.Sheets(i).Range("C:C"))
m = xlBook.Application.CountA(xlBook.Sheets(i).Range("2:2"))
y = Split(xlBook.Sheets(i).Cells(1, m).Address, "$")(1)
DoCmd.TransferSpreadsheet acImport, 8, sheetname, File_Name, True, sheetname & "!B1:" & y & "1"
DoCmd.TransferSpreadsheet acImport, 8, sheetname, File_Name, False, sheetname & "!B3:" & y & j
End If
End If
Next
xlApp.Quit
Set xlApp = Nothing
Next
End If
End Sub
当运行到DoCmd.TransferSpreadsheet acImport, 8, sheetname, File_Name, False, sheetname & "!B3:" & y & j 就出现F1不存在错误啦。。
原来刚开始的时候两段导入的代码都如下:
DoCmd.TransferSpreadsheet acImport, 8, sheetname, File_Name, False , sheetname & "!B1:" & y & "1"
DoCmd.TransferSpreadsheet acImport, 8, sheetname, File_Name, False, sheetname & "!B3:" & y & j
这样可以导入成功的,但是字段名称都是F1和F2之类的,,我做交叉查询不方便,后来发现修改那个FALSE为TRUE可以把第一行作为字段名称,改了之后又发现F1不存在错误。。无语了。。请求各位大侠帮忙。谢了。
|
|