2017-06-01 64 views
0

我有這個子例程來打開/關閉Application的一些屬性。聲明爲應用程序類型變量的子參數

Public Sub OPTIMIZE_VBA(ByVal isOn As Boolean) 
Dim bHolder As Boolean 
bHolder = Not isOn 
On Error Resume Next 
With Application 
    .DisplayAlerts = bHolder 
    .ScreenUpdating = bHolder 
    .EnableEvents = bHolder 
    .Calculation = IIf(isOn, xlCalculationManual, xlCalculationAutomatic) 
    .Calculate 
    If .VERSION > 12 Then .PrintCommunication = bHolder 
End With 
On Error GoTo 0 
End Sub 

說是有應用程序的不同實例,我想開啓/關閉相同的屬性,我將如何能夠修改此代碼,以接受參數/參數爲不同的應用程序? 我期待着像;

Public Sub OPTIMIZE_VBA(ByVal isOn As Boolean, Optional ByVal ExApp As Excel.Application = thisApplication) 
' rest of the code 
End Sub 

有了這個,我可以這樣稱呼它;

Sub Create_New_Excel_and_Disable_Properties() 
'<~ Declare and prepare the new application 
    Dim NewExcel As Excel.Application 
    Set NewExcel = New Excel.Application 

'<~ declare and set the workbook variable 
Dim ExcelWbk As Excel.Workbook 
Set ExcelWbk = NewExcel.Workbooks.Open("folder\template.xlsx") 

'<~ call the sub that disables the Application.properties 
OPTIMIZE_VBA False, NewExcel 
End Sub 

回答

3
Public Sub OPTIMIZE_VBA(ByVal isOn As Boolean, Optional ByVal ExApp As Excel.Application) 

If IsEmpty(ExApp) Or ExApp Is Nothing Then 
    Set ExApp = Application 
End If 

' rest of the code 
End Sub 
+1

我猜你必須使用'set' – FunThomas

+0

對不起 - 今天早上一直在用C#玩...... –

+0

我可以假設我將無法將exapp設置爲應用程序嗎? –

3

方式一:

Public Sub OPTIMIZE_VBA(ByVal isOn As Boolean, Optional ByVal ExApp As Excel.Application = Nothing) 

    If ExApp Is Nothing Then Set ExApp = Application 
    ' rest of the code 

End Sub 
您的意見
+0

兩者都十分讚賞。 –