Excel vba:如果将属性添加到类中,相同的代码会变慢

问题描述 投票:0回答:1

我有一个使用Client类的主子:使用100 000 Clients创建一个数组并在数组100上循环,每次为每个Client设置一个不同的随机数。

Sub start()

    Application.ScreenUpdating = False

    Dim i As Long
    Dim j As Long

    Dim clientsColl() As Client
    ReDim clientsColl(1 To 100000) As Client

    For j = 1 To 100000
        Set clientsColl(j) = New Client
        clientsColl(j).setClientName = "Client_" & j

        Application.StatusBar = "Getting client " & j

        DoEvents
    Next

    Dim clientCopy As Variant
    For i = 1 To 100
        For Each clientCopy In clientsColl
            clientCopy.generateRandom
        Next

        Application.StatusBar = "Calculating " & i

        DoEvents
    Next

    MsgBox ("done")

    Application.StatusBar = False
    Application.ScreenUpdating = True

End Sub

客户类:

Option Explicit

Private clientname As String
Private identityNumber As String
Private creditRating As String

Private contractTenor As Long
Private contractNumber As String
Private contractRate As Double

Private totalReserves As Double
Private totalReservesRate As Double

Private debtType As String
Private totalDebt As Double

Private lossRatio As Double
Private totalLoss As Variant
Private totalProfit As Double

Private totalPd As Double
Private totalLgd As Double

Private simulationCount As Long
Private randomNumber As Double
Private outcome As Integer

Private loss As Double
Private profit As Double

Private sumLosses() As Double
Private sumProfits() As Double
Private sumResults() As Double

Private averageDebtInfo As Double

Public Sub generateRandom()
    randomNumber = Rnd()
End Sub

Public Property Get getClientName()
    getClientName = clientName
End Property

Public Property Let setClientName(value As String)
    clientName = value
End Property

但是,此代码运行时间不同,具体取决于Client类是否具有GetLet属性。上面发布的类的当前版本大约在25秒内运行。如果我添加几个Get属性来获得像identityNumbercontractRate这样的东西需要1 minute 25 seconds

为什么添加简单的Get属性对代码影响如此之大?可以做些什么吗?我承担不起这段代码运行超过30秒..

excel vba excel-vba class oop
1个回答
0
投票

运行宏时,可以使用以下代码禁用应用程序功能。

参考文献:

http://www.vbaexpress.com/kb/getarticle.php?kb_id=1035 https://wellsr.com/vba/2017/excel/speed-up-VBA-macro-with-these-subroutines/

Sub SpeedOff()
     'Turns on the time wasters
     With Application
         .Calculation = xlCalculationAutomatic
         .ScreenUpdating = True
         .EnableEvents = True
         .DisplayAlerts = True
         .Cursor = xlDefault
         .StatusBar = False
         .EnableCancelKey = xlInterrupt
     End With
End Sub

Sub SpeedOn()
    'Turns off the time wasters
    With Application
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
        .DisplayAlerts = False
        .Cursor = xlWait
        .EnableCancelKey = xlErrorHandler
    End With
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.