我在Access 2010中有一个VB窗体,打开一个文件对话框来进行Excel选择。我将文件路径作为字符串发送到我的变量:目录(directory = strPath
)以打开工作簿并将其内容复制到我当前的工作簿中。如果你打算一次使用这个工具,那工作正常。这是当你导入一个文件,然后另一个在相同的目录中发生错误。VBA打开工作簿错误
不工作的例子:
选择C:\桌面\ File1.xls,进口
选择C:\桌面\ File2.xls,进口
错误:
Run-time error '1004':
A document with the name 'Tool.xlsm' is already open. You cannot open two documents with the same name, even if the documents are in different folders. To open the second document, either close the document that's currently open, or rename one of the documents.
工作实例(单独文件夹):
选择C:\桌面\ File1.xls,进口
选择C:\桌面\ TestFolder \ File2.xls,进口
Public Sub CommandButton1_Click()
Dim intChoice As Integer
Dim strPath As String
Application.EnableCancelKey = xlDisabled
'only allow the user to select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
strPath = Application.FileDialog(_
msoFileDialogOpen).SelectedItems(1)
'print the file path to sheet 1
TextBox1 = strPath
End If
End Sub
Public Sub CommandButton2_Click()
Dim directory As String, FileName As String, sheet As Worksheet, total As Integer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
directory = strPath
FileName = Dir(directory & "*.xls")
Do While FileName <> ""
Workbooks.Open (directory & FileName)
For Each sheet In Workbooks(FileName).Worksheets
total = Workbooks("Tool.xlsm").Worksheets.Count
Workbooks(FileName).Worksheets(sheet.name).Copy _
after:=Workbooks("Tool.xlsm").Worksheets(total)
Next sheet
Workbooks(FileName).Close
FileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableCancelKey = xlDisabled
Application.DisplayAlerts = False
End Sub
在调试模式下它不喜欢
Workbooks.Open (directory & FileName)
任何建议,以消除此错误?
那么,你的代码试图打开目录中的所有Excel文件。其中之一就是'tool.xlsm',它已经被加载(是的,'* .xls'模式[也可以找到'xlsm'文件](http://blogs.msdn.com/b/oldnewthing/archive /2014/03/13/10507457.aspx))。 – GSerg
另外,directory = strPath什么都不做,因为它没有在这个子文件中声明 – EvenPrime
我把strPath改成了一个全局变量。有关将此更改为仅打开1个文件的任何提示? – user3596788