2014-12-05 3 views
7

계속이 1004 런타임 오류가 발생합니다. 내 프로그래밍 방식을 약간 줄여서 Programception이 아니 었습니다. Excel 2010을 사용하여 .xls 파일을 저장해야 할 수도 있습니다. 확실하지 않다. Auto_Root.xls가 열리면파일을 열고 값으로 저장하는 매크로를 실행하는 매크로 - 런타임 오류 1004

  1. 는 순차적으로 다른 디렉토리에 7 개 파일 을 열고 하위 업데이트를() Panel.xls
  2. 패널이 열리고 열리고 실행 하위에 Auto_Open()를 실행하는 모든라는 Auto_Update.xls
  3. Auto_Update.xsl은 각각 개의 파일을 순차적으로 열어 자신의 플랫 복사본을 다른 디렉터리에 저장하는 Sub Flat을 열고 실행합니다.

7 개의 Auto_Update.xls 파일을 각각 열어서 독립적으로 실행 했으므로 오류없이 실행됩니다. Auto_Root에서 모두 실행하면 런타임 오류 1004가 발생합니다. 그리고 CurrentWB.Save는 파일 중 하나에서 강조 표시됩니다. 나는 CurrentWB.Save를 CurrentWB.SaveAs Filename : = TargetFile, FileFormat : = xlNormal로 대체하고 동일한 런타임 오류를 수신했습니다.

첨부 된 코드는 있습니다.

AutoRoot.xls! 자동 업데이트

Sub auto_open() 
Application.CutCopyMode = False 
Dim PanelFilePath As String 
Dim PanelFileName As String 
Dim PanelLocation As String 
Dim PanelWB As Workbook 
    PanelFilePath = "D:\umc\UMC Production Files\Automation Files\" 
    PanelFileName = "Panel.xls" 
    PanelLocation = PanelFilePath & Dir$(PanelFilePath & PanelFileName) 
     Set PanelWB = Workbooks.Open(Filename:=PanelLocation, UpdateLinks:=3) 
      PanelWB.RunAutoMacros Which:=xlAutoOpen 
      Application.Run "Panel.xls!Update" 
      PanelWB.Close 
    Call Shell("D:\umc\UMC Production Files\Automation Files\Auto.bat", vbNormalFocus) 
Application.Quit 
End Sub 

Panel.xls! 업데이트

Sub Update() 
Dim RowNumber As Long 
Dim AutoUpdateTargetFile As String 
Dim AutoUpdateWB As Workbook 
For RowNumber = 1 To (Range("AutoUpdate.File").Rows.Count - 1) 
    If (Range("AutoUpdate.File").Rows(RowNumber) <> "") Then 
     AutoUpdateTargetFile = Range("Sys.Path") & Range("Client.Path").Rows(RowNumber) & Range("AutoUpdate.Path ").Rows(RowNumber) & Range("AutoUpdate.File").Rows(RowNumber) 
     Set AutoUpdateWB = Workbooks.Open(Filename:=AutoUpdateTargetFile, UpdateLinks:=3) 
      AutoUpdateWB.RunAutoMacros Which:=xlAutoOpen 
      Application.Run "Auto_Update.xls!Flat" 
      AutoUpdateWB.Close 
    End If 
    Next RowNumber 
End Sub 

AutoUpdate.xls!

Sub Flat() 
Dim RowNumber As Long 'Long Stores Variable 
Dim SheetNumber As Long 
Dim TargetFile As String 'String Stores File Path 
Dim BackupFile As String 
Dim CurrentWB As Workbook 'Workbook Stores Workbook 
For RowNumber = 1 To (Range("File").Rows.Count - 1) 
'Loops through each file in the list and assigns a workbook variable. 
    If (Range("File").Rows(RowNumber) <> "") Then 
     TargetFile = Range("Sys.Path") & Range("Path").Rows(RowNumber) & Range("File").Rows(RowNumber) 'Target File Path 
     BackupFile = Range("Report.Path") & Range("Path").Rows(RowNumber) & Range("SubFolder") & Range("File").Rows(RowNumber) 'Backup File Path 
Set CurrentWB = Workbooks.Open(Filename:=TargetFile, UpdateLinks:=3) 'Sets CurrentWB = to that long name. This becomes the name of the workbook. 
    CurrentWB.RunAutoMacros Which:=xlAutoOpen 'Enables Macros in Workbook 
    CurrentWB.SaveAs Filename:=TargetFile, FileFormat:=56 
     For SheetNumber = 1 To Sheets.Count 'Counts Worksheets in Workbook 
      Sheets(SheetNumber).Select 'Selects All Worksheets in Workbook 
      If (Sheets(SheetNumber).Name <> "What If") Then 
       Sheets(SheetNumber).Unprotect ("UMC626") 'Unprotects Workbook 
       Cells.Select 'Selects Data in Workbook 
       Range("B2").Activate 
       With Sheets(SheetNumber).UsedRange 
        .Value = .Value 
       End With 
       Sheets(SheetNumber).Protect Password:="UMC626", DrawingObjects:=True, Contents:=True, Scenarios:=True 'Protects Workbook 
      End If 
     Next SheetNumber 'Runs Through Iteration 
     Sheets(1).Select 
     Range("A1").Select 'Saves each workbook at the top of the page 
     CurrentWB.SaveAs Filename:=BackupFile, FileFormat:=56, Password:="", WriteResPassword:="", _ 
     ReadOnlyRecommended:=False, CreateBackup:=False 'Saves Workbook in Flatten File Location 
    CurrentWB.Close 'Closes Workbook 
    End If 'Ends Loop 
Next RowNumber 'Selects Another Account 
End Sub 

플랫 내가 지금까지했던 어떤.

  1. 각 개별 자동 업데이트 파일은 켜져있을 때 작동합니다.
  2. Application.Run "Auto_Update.xls! Flat"이 Panel.xls! Update에서 제거되면 모든 AutoUpdate.xls 파일이 오류없이 열리고 닫힙니다.
  3. Panel.xls! 7 AutoUpdate 파일 중 3 개만 업데이트하면 .... 3. 아무런 오류없이 실행됩니다.

난 그냥 코드 주위에 마이크로 소프트 작품을 발견 런타임 오류 (1004)

말을하지 않고 모든 7을 실행 얻을 수없는 것. 비록 그것을 구현하는 방법을 잘 모르겠습니다.

Sub CopySheetTest() 
    Dim iTemp As Integer 
    Dim oBook As Workbook 
    Dim iCounter As Integer 

    ' Create a new blank workbook: 
    iTemp = Application.SheetsInNewWorkbook 
    Application.SheetsInNewWorkbook = 1 
    Set oBook = Application.Workbooks.Add 
    Application.SheetsInNewWorkbook = iTemp 

    ' Add a defined name to the workbook 
    ' that RefersTo a range: 
    oBook.Names.Add Name:="tempRange", _ 
     RefersTo:="=Sheet1!$A$1" 

    ' Save the workbook: 
    oBook.SaveAs "c:\test2.xls" 

    ' Copy the sheet in a loop. Eventually, 
    ' you get error 1004: Copy Method of 
    ' Worksheet class failed. 
    For iCounter = 1 To 275 
     oBook.Worksheets(1).Copy After:=oBook.Worksheets(1) 
     'Uncomment this code for the workaround: 
     'Save, close, and reopen after every 100 iterations: 
     If iCounter Mod 100 = 0 Then 
      oBook.Close SaveChanges:=True 
      Set oBook = Nothing 
      Set oBook = Application.Workbooks.Open("c:\test2.xls") 
     End If 
    Next 
End Sub 

http://support.microsoft.com/kb/210684/en-us

+2

어떤 줄이 오류를 발생 시키나요? –

+2

'File'및 'Path'의 NAMED 범위를 올바르게 정의하고 ONE 셀의 이름을 'Sys.Path', 'Report.Path'및 'SubFolder'로 지정 했습니까? 또한, 'Sys.Path'(및 기타 정보)에 어떤 값을 가지고 있습니까? –

+1

통합 문서에 읽기 전용 속성이 설정되어 있습니까? – Sorceri

답변

7

을 얻을 수 있도록 enopugh있는 알려진 문제입니다 바랍니다.

Copying worksheet programmatically causes run-time error 1004 in Excel

나는 그게 문제가 나타납니다 얼마나 많은 시트 플랫이 루프를하지만 확실하지 않다. 특히 인용 :이 문제는 통합 문서를 정의 된 이름을 줄 때 발생 먼저 저장하지 않고 워크 시트를 여러 번 복사 인해 사용자가 작성한 수준으로 통합 문서

을 종료 할 수

별도의 워크 북을 사용하여 Update 서브 루틴의 범위를 제한하는 것으로 시작하는 것이 좋습니다. 그런 식으로 많은 디자인이 있지만 자동 열기와 업데이트 사이에 정수 인수를 앞뒤로 반복하여 전달할 수도 있습니다. 이렇게하면 Panel.xls를 여러 번 닫고 다시 열 수 있으며 중단 한 부분부터 정확하게 시작할 수 있습니다.

+0

어떻게 그럴 수 있습니까? –

+1

"Update (loopCount As Integer)"구문을 사용하여 Update에 인수를 추가 한 다음 Update 함수에서 변수를 세 번 사용하면 (제한 사항으로 보이는 경우) 자동 열기로 다시 전달합니다.자동 열기에 루프를 추가하여 loopCount를 확인하고 모든 파일이 업데이트되었는지 확인해야합니다. 이렇게하면 런타임 오류를 피하기 위해 각 파일을 열거 나 닫을 수 있습니다. 인수 전달에 대한 자세한 내용은 여기를 참조하십시오. http://msdn.microsoft.com/en-us/library/aa263527%28v=vs.60%29.aspx –

+0

대신 한 번 실행하면 차이가 있습니까? 그것을 다시 지나기 전에 세 번이나? –

2
텍스트 분명

아니고,하지만 프로 시저 "플랫"열려는 파일 내부에 그렇다면 그것은 자동 개방 매크로에 의해 호출되고? 원본 통합 문서에서 매크로를 실행하고 열려있는 통합 문서의 자동 열기 매크로에서 매크로를 실행하지 않는 것처럼 들리는 것 같습니다. 이것이 사실 인 경우 작업 노트를 열 때 "업그레이드"마법사가있는 통합 문서 중 하나에서 비슷한 작업을 수행합니다. 그러나 업그레이드 중이므로 열려있는 다른 통합 문서에도 작업 영역이 있습니다. 업 그레 이드 마법사, 그래서뿐만 아니라 화재하는 데 사용됩니다.Excel의 숨겨진 인스턴스에서 다른 통합 문서를 열어이 문제를 해결했으며 내 자동 열기 매크로 내에 통합 문서의 보이는 상태를 쿼리하고 숨겨진 경우 실행하지 않는 코드 줄을 사용했습니다. 그래서 마법사가

'Check if the ODS code is populated or default xxx, if so invoke the upgrade wizard 
    'but only if the application is visible 
    If (ActiveWorkbook.Names("Trust_ODS_Code").RefersToRange.Value = "xxx" _ 
     Or Len(ActiveWorkbook.Names("Trust_ODS_Code").RefersToRange.Value) = 0) _ 
     And Me.Application.visible = True Then 
      'run the upgrade wizard 
     frmCSCWizardv8.Show 
    End If 

를 실행할 경우 제어 아래 코드 그것 "그리고 Me.Application.visible"에서 이렇게하면 엑셀 별도의 인스턴스에서 통합 문서를 열어야합니다. 아래의 코드는이 작업을 수행하는 코드의 조각입니다 이것은 당신이 아래에 링크 된 Microsoft의 문서를 바탕으로 아이디어

 Dim lRet 
     Dim i As Integer, j As Integer 
     Dim FoundSheet As Boolean 

     'Because the wizard opens the old DCS in a hidden instance of Excel, it is vital that we close this if 
     'anything goes wrong, so belt and braces, close it every time the user presses the button 
     'Switch off the error handling and the display alerts to avoid any error messages if the old dcs has 
     'never been opened and the hidden instance does not exist 
    Application.DisplayAlerts = False 
    On Error Resume Next 
     book.Close SaveChanges:=False 
     app.Quit 
     Set app = Nothing 
    Application.DisplayAlerts = True 

     'set error handling 
    On Error GoTo Err_Clr 

     'populate the status bar 
    Application.StatusBar = "Attempting to open File" 

     'Default method Uses Excel Open Dialog To Show the Files 
    lRet = Application.GetOpenFilename("Excel files (*.xls;*.xlsx;*.xlsm;*.xlsb), *.xls;*.xlsx;*.xlsm;*.xlsb") 

     'If the user selects cancel update the status to tell them 
    If lRet = False Then 
     Me.lstOpenDCSStatus.AddItem "No file selected" 
     'if the user has selected a file try to open it 
    Else 
      'This next section of code creates a new instance of excel to open the selected file with, as this allows us to 
      'open it in the background 
     OldDCS = lRet 
     Application.StatusBar = "Attempting to open File - " & lRet 
     app.visible = False 'Visible is False by default, so this isn't necessary, but makes readability better 
     Set book = app.Workbooks.Add(lRet) 
     Application.StatusBar = "Opened File - " & lRet