2016-11-07 92 views
0

這不是最重要的問題,而且更具腐蝕性。 我在我的所有子程序中都使用了application.screenupdating等。 我通常會有多個模塊和子例程,所有這些模塊和子例程都有優化代碼。優化vba - 應用程序。

我想知道是否有辦法不必在每個模塊中編寫代碼?

我想我在尋找類似的是,可以任意模塊或子程序中使用全局聲明變量的概念,而無需將它們定義每次

with application 
    .ScreenUpdating = False 
    .DisplayStatusBar = False 
end with 
+0

你需要xlsb文件,如果你想分享excel代碼或者vbscript也可以幫到你。 –

+0

對不起?我不明白你的意思... – user1

+0

這[示例](http://codereview.stackexchange.com/questions/117037/vba-class-to-persist-and-restore-excel-application-properties)使用類來堅持並恢復應用程序設置。或者以類似的方式另一種[方法](http://codereview.stackexchange.com/questions/142793/applicationsettings-class-for-disabling-restoring-application-state)。 – ThunderFrame

回答

2

如果函數設置爲true,則可以聲明布爾函數,然後將.ScreenUpdating設置爲false,反之亦然。

Public Function ApplicationOptimization(BOOLEAN_TRIGGER As Boolean) 
With Application 
    Select Case BOOLEAN_TRIGGER 
    Case True 
    .ScreenUpdating = False 
    .DisplayStatusBar = False 
    .Calculation = xlCalculationManual 
    Case False 
    .ScreenUpdating = True 
    .DisplayStatusBar = True 
    .Calculation = xlCalculationAutomatic 
    End Select 
End With 
End Function 

Public Sub Use() 
ApplicationOptimization (False) 'False or True 
End Sub 

您可以在單個模塊中創建此功能,然後在任何其他模塊或窗體中引用它。這應該可以節省每個模塊中的重複代碼。道歉,如果這不是你要找的。

+0

什麼是「不」的部分? – user1

+0

我不知道它的工作? – user1

+0

'not'集合傳遞'ApplicationOptimization()'的相反值。因此,如果將ApplicationOptimization()設置爲true,那麼'.properties'設置爲false。 – Nulled

0

你可以做一個碼殼發電機。加入微軟引用窗體2.0對象庫,然後:

Public Sub SubShell(SubName As String) 
    Dim s As String 
    Dim DataObj As New MSForms.DataObject 

    s = "Sub " & SubName & "()" & vbCrLf 
    s = s & String(4, " ") & "With Application" & vbCrLf 
    s = s & String(8, " ") & ".ScreenUpdating = False" & vbCrLf 
    s = s & String(8, " ") & ".DisplayStatusBar = False" & vbCrLf 
    s = s & String(4, " ") & "End With" & vbCrLf & vbCrLf 
    s = s & String(4, " ") & "'Insert Code" & vbCrLf & vbCrLf 
    s = s & String(4, " ") & "With Application" & vbCrLf 
    s = s & String(8, " ") & ".ScreenUpdating = True" & vbCrLf 
    s = s & String(8, " ") & ".DisplayStatusBar = True" & vbCrLf 
    s = s & String(4, " ") & "End With" & vbCrLf 
    s = s & "End Sub" & vbCrLf 
    DataObj.SetText s 
    DataObj.PutInClipboard 
End Sub 

如果你現在在即時窗口中鍵入SubShell "Test",您希望子定位光標,然後再粘貼,你會看到下面的出現:

Sub Test() 
    With Application 
     .ScreenUpdating = False 
     .DisplayStatusBar = False 
    End With 

    'Insert Code 

    With Application 
     .ScreenUpdating = True 
     .DisplayStatusBar = True 
    End With 
End Sub 
+0

這是整潔!但不是我想要實現的不幸 – user1

+0

你的問題是關於如何避免鍋爐板代碼。我的建議並沒有避免鍋爐板,但通過自動生成來節省擊鍵。我同意首先避免它的需要。 –