此Excel VBAmacros太慢

有没有办法加快这个代码。 我对VBA非常陌生(本周才真正开始),并且试图编写这个macros来根据财务模型自动计算需要借入的金额。

为了给出一些上下文,这个单元格在另一个工作表上通知一个高峰借款需求(pbr)单元格,但是当你增加所需的设施的价值(fr)时,这个单元格完全是由于利息和其他各种费用而被借用的。

我已经创build了一系列的while循环来获得这个fr值到最接近的10,000,但是是不可思议的慢。 我确定必须有一个更优雅的方式来写这个,但我似乎无法弄清楚。 最好我想把它变成一个function,而不是一个子,但我甚至不知道这是否可能。

这是迄今为止的代码,任何帮助,你可以给予将非常感激!

' Sub procedure to calculate the peak borrowing requirement' Sub calculateFacilityRequiredButton() Dim pbr As Long ' stores the initial peak borrowing requirement from the viability page Dim fr As Long ' stores the facility required from the inputs page ' set pbr variable as the value from the viability page Worksheets("Viability").Activate pbr = Cells(9, "k").Value ' set the starting value at the current peak borrowing rate from the viability page Worksheets("Viability").Activate fr = Cells(9, "K").Value Do While fr <= pbr If fr <= pbr Then fr = fr + 1000000 Worksheets("Inputs").Activate Range("N47").Value = fr Worksheets("Viability").Activate pbr = Cells(9, "k").Value End If Loop Do While fr > pbr + 100000 If fr > pbr + 100000 Then fr = fr - 100000 Worksheets("Inputs").Activate Range("N47").Value = fr Worksheets("Viability").Activate pbr = Cells(9, "k").Value End If Loop Do While fr > pbr + 10000 If fr > pbr + 10000 Then fr = fr - 10000 Worksheets("Inputs").Activate Range("N47").Value = fr Worksheets("Viability").Activate pbr = Cells(9, "k").Value End If Loop Worksheets("Inputs").Activate End Sub 

While循环似乎与条件相同。 从我所看到的情况来看,它只会在While循环中执行一个循环。 所以我不认为你需要while循环。 另外,正如其他人所说,不要尝试激活表。 合格您的工作表为:

 Dim oW As Worksheet: Set oW = ThisWorkbook.Worksheets("Viability") 

你可以使用它作为oW.Range("N47").Value = fr 。 这应该指向正确的方向

尽量不要激活,做这样的事情

worksheets("Destination").range("A1").value=worksheets("Source").range("a1").value

引用工作表,而不是激活它们。

如果有人有类似的,可比较的问题,以供参考。 这是根据Zac的答案为我工作的解决scheme。

 Sub CalculateFR() ' Sub procedure to calculate the peak borrowing requirement' Dim pbr As Long ' stores the initial peak borrowing requirement from the viability page Dim fr As Long ' stores the facility required from the inputs page Dim oWV As Worksheet Dim oWI As Worksheet Set oWV = Sheets("Viability") Set oWI = Sheets("Inputs") ' set pbr variable as the value from the viability page pbr = oWV.Range("K9").Value ' set the starting value at the current peak borrowing rate from the viability page fr = oWV.Range("K9").Value Do While fr <= pbr fr = fr + 1000000 oWI.Range("N47").Value = fr pbr = oWV.Range("K9").Value Loop Do While fr <= pbr + 100000 fr = fr + 100000 oWI.Range("N47").Value = fr pbr = oWV.Range("K9").Value Loop Do While fr <= pbr + 10000 fr = fr + 10000 oWI.Range("N47").Value = fr pbr = oWV.Range("K9").Value Loop End Sub