2016-10-30 2 views
0

두 개의 함수에 대한 호출을 만들기 위해 Public Sub를 얻으려고합니다. 각 함수는 동일한 데이터 시트에서 다른 피벗 테이블을 만듭니다. 나는 두 함수가 독립적으로 작동한다는 것을 알고 있지만 하나의 하위 함수에 결합하면 "응용 프로그램 정의 또는 객체 정의 오류"가 계속 발생합니다.Mutiple Function Call - Public Sub

아래 매크로는 첫 번째 함수를 실행하고 원하는 피벗 테이블을 만듭니다. 두 번째 함수에 도달하면 중지되고 위에서 언급 한 응용 프로그램 또는 개체 정의 오류가 표시됩니다. 각 기능을 독립적으로 정의했기 때문에 왜 문제가 발생하는지 확신 할 수 없습니다.

Option Explicit 

Public Sub RunPivots() 
Call BuildPivot1("Travel Payment Data by Employee") 
Call BuildPivot2("Travel Payment Data by Acct Dim") 

End Sub 

Function BuildPivot1(paramSheet As String) 
On Error GoTo ErrHandle 
Dim FinalRow   As Long 
Dim DataSheet   As String 
Dim PvtCache   As PivotCache 
Dim PvtTbl    As PivotTable 
Dim PvtFld    As PivotField 
Dim DataRng    As Range 
Dim TableDest   As Range 
Dim ws     As Worksheet 

For Each ws In ThisWorkbook.Sheets 
    If ws.Name Like "*SQL" & "*" Then 
     '~~> This check is required to ensure that you don't get an error 
     '~~> if there is only one sheet left and it matches the delete criteria 
     If ThisWorkbook.Sheets.Count = 1 Then 
      MsgBox "There is only one sheet left and you cannot delete it" 
     Else 
      '~~> This is required to supress the dialog box which excel shows 
      '~~> When you delete a sheet. Remove it if you want to see the 
      '~~~> Dialog Box 
      Application.DisplayAlerts = False 
      ws.Delete 
      Application.DisplayAlerts = True 
     End If 
    End If 
Next 

FinalRow = Cells(Rows.Count, 1).End(xlUp).Row 

DataSheet = "Export Worksheet" 
' set data range for Pivot Table 
Set DataRng = Sheets(DataSheet).Range(Cells(1, 1), Cells(FinalRow, 15)) 

' check if worksheet exists 
Dim currws As Worksheet 
For Each currws In ActiveWorkbook.Worksheets 
    If currws.Name = paramSheet Then 
     Set ws = Worksheets(paramSheet) 
     Exit For 
    End If 
Next currws 

' create new worksheet if does not exist 
If ws Is Nothing Then 
    Set ws = Worksheets.Add 
    ws.Name = paramSheet 
End If 

' set range for Pivot table placement 
Set TableDest = Sheets(paramSheet).Cells(1, 1) 

' create pivot cache 
Set PvtCache = ActiveWorkbook.PivotCaches.Create(_ 
      SourceType:=xlDatabase, _ 
      SourceData:=DataRng, _ 
      Version:=xlPivotTableVersion15) 

'check if "PivotTable4" Pivot Table exists 
Dim currpvt As PivotTable 
For Each currpvt In ws.PivotTables 
    If currpvt.Name = "PivotTable4" Then 
     Set PvtTbl = ws.PivotTables("PivotTable4") 
     Exit For 
    End If 
Next currpvt 

' create new pivot table if does not exist 
If PvtTbl Is Nothing Then 
    Set PvtTbl = PvtCache.CreatePivotTable(_ 
     TableDestination:=TableDest, _ 
     TableName:="PivotTable4") 
End If 

With PvtTbl.PivotFields("Security Org") 
    .Orientation = xlRowField 
    .Position = 1 
End With 
With PvtTbl.PivotFields("Fiscal Month") 
    .Orientation = xlRowField 
    .Position = 2 
End With 
With PvtTbl.PivotFields("Budget Org") 
    .Orientation = xlRowField 
    .Position = 3 
End With 
With PvtTbl.PivotFields("Vendor Name") 
    .Orientation = xlRowField 
    .Position = 4 
End With 
With PvtTbl.PivotFields("Fiscal Year") 
    .Orientation = xlRowField 
    .Position = 5 
End With 
With PvtTbl.PivotFields("Fiscal Year") 
    .Orientation = xlColumnField 
    .Position = 1 
End With 

Range("B:E").Select 
Range(Selection, Selection.End(xlDown)).Select 
Selection.NumberFormat = "$#,##0.00" 
Range("B1").Select 
PvtTbl.CompactLayoutColumnHeader = _ 
    "Fiscal Year" 
Range("A2").Select 
PvtTbl.CompactLayoutRowHeader = _ 
    "Security Org and Vendor" 
Range("G8").Select 

' Add data field if does not exist 
On Error Resume Next 
PvtTbl.AddDataField PvtTbl.PivotFields("Dollar Amount"), "Sum of Dollar Amount", xlSum 
PvtTbl.PivotFields("Budget Org").ShowDetail = _ 
    False 
Exit Function 

ErrHandle: 
MsgBox Err.Number & " - " & Err.Description, vbCritical, "RUNTIME ERROR" 
Exit Function 
End Function 

Function BuildPivot2(paramSheet As String) 
On Error GoTo ErrHandle 
Dim FinalRow   As Long 
Dim DataSheet   As String 
Dim PvtCache   As PivotCache 
Dim PvtTbl    As PivotTable 
Dim PvtFld    As PivotField 
Dim DataRng    As Range 
Dim TableDest   As Range 
Dim ws     As Worksheet 

For Each ws In ThisWorkbook.Sheets 
    If ws.Name Like "*SQL" & "*" Then 
     '~~> This check is required to ensure that you don't get an error 
     '~~> if there is only one sheet left and it matches the delete criteria 
     If ThisWorkbook.Sheets.Count = 1 Then 
      MsgBox "There is only one sheet left and you cannot delete it" 
     Else 
      '~~> This is required to supress the dialog box which excel shows 
      '~~> When you delete a sheet. Remove it if you want to see the 
      '~~~> Dialog Box 
      Application.DisplayAlerts = False 
      ws.Delete 
      Application.DisplayAlerts = True 
     End If 
    End If 
Next 

FinalRow = Cells(Rows.Count, 1).End(xlUp).Row 

DataSheet = "Export Worksheet" 
' set data range for Pivot Table 
DataSheet = "Export Worksheet" 
' set data range for Pivot Table 
With Sheets(DataSheet) 
    Set DataRng = .Range(Cells(1, 1), .Cells(FinalRow, 15)) 
End With 

' check if worksheet exists 
Dim currws As Worksheet 
For Each currws In ActiveWorkbook.Worksheets 
    If currws.Name = paramSheet Then 
     Set ws = Worksheets(paramSheet) 
     Exit For 
    End If 
Next currws 

' create new worksheet if does not exist 
If ws Is Nothing Then 
    Set ws = Worksheets.Add 
    ws.Name = paramSheet 
End If 

' set range for Pivot table placement 
Set TableDest = Sheets(paramSheet).Cells(1, 1) 

' create pivot cache 
Set PvtCache = ActiveWorkbook.PivotCaches.Create(_ 
      SourceType:=xlDatabase, _ 
      SourceData:=DataRng, _ 
      Version:=xlPivotTableVersion15) 

'check if "PivotTable4" Pivot Table exists 
Dim currpvt As PivotTable 
For Each currpvt In ws.PivotTables 
    If currpvt.Name = "PivotTable4" Then 
     Set PvtTbl = ws.PivotTables("PivotTable4") 
     Exit For 
    End If 
Next currpvt 

' create new pivot table if does not exist 
If PvtTbl Is Nothing Then 
    Set PvtTbl = PvtCache.CreatePivotTable(_ 
     TableDestination:=TableDest, _ 
     TableName:="PivotTable4") 
End If 

With PvtTbl.PivotFields("Fiscal Year") 
    .Orientation = xlColumnField 
    .Position = 1 
End With 
With PvtTbl.PivotFields("Fund") 
    .Orientation = xlRowField 
    .Position = 1 
End With 
With PvtTbl.PivotFields("Budget Org") 
    .Orientation = xlRowField 
    .Position = 2 
End With 
With PvtTbl.PivotFields("Cost Org") 
    .Orientation = xlRowField 
    .Position = 3 
End With 

Range("B:E").Select 
Range(Selection, Selection.End(xlDown)).Select 
Selection.NumberFormat = "$#,##0.00" 
Range("B1").Select 
PvtTbl.CompactLayoutColumnHeader = _ 
    "Fiscal Year" 
Range("A2").Select 
PvtTbl.CompactLayoutRowHeader = _ 
    "Security Org and Vendor" 
Range("G8").Select 

' Add data field if does not exist 
On Error Resume Next 
PvtTbl.AddDataField PvtTbl.PivotFields("Dollar Amount"), "Sum of Dollar Amount", xlSum 
PvtTbl.PivotFields("Budget Org").ShowDetail = _ 
    False 
Exit Function 

ErrHandle: 
MsgBox Err.Number & " - " & Err.Description, vbCritical, "RUNTIME ERROR" 
Exit Function 

End Function 
+0

당신은 어떤 디버깅을 수행 했습니까? 어떤 줄이 오류를 던집니까? – OldUgly

+0

방금 ​​1004 오류가 발생하면 회선을 가리키고 있지 않음 – Cjamros

+0

모든 Cells() 및 Range() 호출이 워크 시트 개체로 규정되어 있는지 확인해야합니다. –

답변

3

모든 Cells() 및 Range() 호출이 워크 시트 개체로 정규화되어 있어야합니다. 예를 들면 다음과 같습니다 DataSheet 워크 시트가 activesheet없는 경우

Set DataRng = Sheets(DataSheet).Range(Cells(1, 1), Cells(FinalRow, 15)) 

이 실패합니다. 이 같은

수정은 :

With Sheets(DataSheet) 
    Set DataRng = .Range(.Cells(1, 1), .Cells(FinalRow, 15)) 
End With 
+0

꽤 희망적 이었지만 운이 없었습니다. 여전히 동일한 응용 프로그램을 정의하거나 개체 정의 오류가 발생합니다. – Cjamros

+0

업데이트 된 코드로 질문을 업데이트하는 데 도움이 될 것입니다. –

+0

데이터 시트 = "내보내기 워크가" 하는 '장 (데이터 시트)를 피벗 테이블 세트 DataRng = .Range 대해 설정된 데이터 범위 (셀 (1, 1), .Cells (FinalRow 15)) 함께 최종 I가 갱신 위의 코드로 두번째 함수. 여전히 같은 오류가 발생합니다. 나는 또한 두 기능에서 모두 시도했지만 실행되지 않습니다. – Cjamros

관련 문제