Access 2010에서 VB 양식을 사용하여 파일 대화 상자를 열어 Excel을 선택합니다. 파일 경로를 내 변수 : directory (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