我遇到了一个随机出现的问题(在我的机器上运行它 - 大约90%的时间都有效,在客户端的机器上进行了几次尝试,它没有100%的工作时间时间) 这是代码:
sub importdata()
Dim dbpath As String
Dim acc As New Access.Application
'bunch of stuff
acc.OpenCurrentDatabase dbpath & "\Database.accdb"
acc.DoCmd.TransferSpreadsheet acImport, 10, "tbl_SalesData", dbpath & "\Dashboard 2015.04.17.xlsm", True, "DataForImport!"
acc.CloseCurrentDatabase
acc.Quit
'bunch of more stuff
end sub
DataForImport是数据所在的工作表。它在一张桌子里;但是,访问无法识别表名"销售"作为导入的范围,所以我选择导入整个工作表。
在客户端的机器上,代码在transferpreadsheet行上出错(尝试用仪表板文件打开另一个excel实例,并说该文件已经打开,错误三千个);但是,在我的机器上它运行得很好。
有没有人遇到过类似的问题?有没有更好的方法将数据从excel推送到访问?如果没有,transferpreadsheet更喜欢关闭文件,所以我需要关闭文件我从(Dashboard)导入数据然后运行那段代码并重新打开它之后呢?
谢谢!
答案:
保存临时文件并从中推送效果很好
Workbooks.Add.SaveAs dbpath & "\tempwb.xlsx"
Set tempwb = Application.Workbooks("tempwb.xlsx")
Application.Workbooks(dashboard).Activate
acc.OpenCurrentDatabase dbpath & "\Database.accdb"
Application.Workbooks(dashboard).Sheets("DataForImport").Copy Before:=tempwb.Sheets(1)
tempwb.Save
tempwb.Close
acc.DoCmd.TransferSpreadsheet acImport, 10, "tbl_SalesData", dbpath & "\tempwb.xlsx", True, "DataForImport!"
Kill dbpath & "\tempwb.xlsx"
acc.CloseCurrentDatabase
acc.Quit
Set acc = Nothing
答案 0 :(得分:1)
理论上,你的代码应该没问题。
实际上,由于Office产品通常不喜欢您尝试做的事情,我强烈建议您在Access中执行所有导入。
然后你只需要一行vba:
DoCmd.TransferSpreadsheet acImport, 10, "tbl_SalesData", dbpath & "\Dashboard 2015.04.17.xlsm", True, "DataForImport!"
...或等效的非VBA宏,可以逐步构建。
答案 1 :(得分:0)
Access.application - >你正在使用早期绑定。您的客户是否有不同版本的Office?您可能希望使用后期绑定重新编写它(例如dim acc as Object,然后设置Acc = CreateObject(“Access.application”))然后您可能会在客户端的计算机上看到与您相同的成功率。
对于传输电子表格,您需要一个已关闭的文件,为了解决这个问题,我使用了一种简单的方法,这是一种类似的方法;
xls.save 'save your current file
filecopy currentpath, dir(currentPath) & "\zzztmp.xls" 'make a copy in the same folder named zzztmp
docmd.transfer here with the TEMP file path
kill dir(currentPath) & "\zzztmp.xls" 'this will delete the temp file and our data is in Access and the user is happy
这样,用户不知道您已保存副本并将其导入访问,但这只是意味着您不必关闭文件并将用户与excel文件混淆,然后重新打开以导入访问。