VBA Excel Sub运行速度非常慢

我试图写这个Sub,它更新(已知)一定数量的列,但不确定数量的行的表。 我在表格的最后一行和表格的第一列中有我需要计算的值。 这是我的代码到目前为止:(它的工作只是运行非常慢)

Sub updateMySheets() Application.DisplayAlerts = False Application.ScreenUpdating = False Application.EnableEvents = False Application.Calculation = xlCalculationManual Dim x, y As Integer 'Looks dynamically for the largest row & column index numrows = Range("C2", Range("C2").End(xlDown)).Rows.Count numcols = Range("C2", Range("C2").End(xlToRight)).Columns.Count Range("C2").Select Dim discount, margin As Double For x = 1 To numrows - 1 discount = ActiveCell.Offset(0, -1).Value For y = 1 To numcols margin = ActiveCell.Offset(numrows - x, y - 1).Value If margin - discount <= 0.0001 Then 'Hier noch ggf. die Cell farbig anpassen ActiveCell.Offset(0, y - 1).Value = "" Else ActiveCell.Offset(0, y - 1).Value = discount / (margin - discount) End If Next ActiveCell.Offset(1, 0).Select Next Application.Calculation = xlCalculationAutomatic Application.DisplayAlerts = True Application.ScreenUpdating = True Application.EnableEvents = True End Sub 

帮助将不胜感激

试试这个,我用'//标注了我的评论,并用标准注释掉了你现有的代码'

 Sub MM() '// You can use "," to Dim multiple variables but you still '// need to declare the data type otherwise it will default '// to type "Variant" which can cause issues later in your code. Dim x As Integer, y As Integer Dim discount As Double, margin As Double ''Looks dynamically for the largest row & column index 'numrows = Range("C2", Range("C2").End(xlDown)).Rows.count 'numcols = Range("C2", Range("C2").End(xlToRight)).Columns.count For Each sh In ActiveWorkbook.Sheets With sh '// Get the row number of the last row in C and minus 1 for the header. numRows = .Cells(.Rows.count, 3).End(xlUp).Row - 1 '// Same logic for the columns numCols = .Cells(2, .Columns.count).End(xlToLeft).Column - 1 '// Never need to ".Select" anything 'Range("C2").Select 'Dim discount, margin As Double (See first comment) For x = 1 To numRows - 1 '// Just use x to determine the row number. 'discount = ActiveCell.Offset(0, -1).value discount = .Cells(x + 1, 2).value For y = 1 To numCols margin = .Cells(x + 1, 3).Offset(numRows - x, y - 1).value If margin - discount <= 0.0001 Then .Cells(x + 1, 3).Offset(0, y - 1).value = "" Else .Cells(x + 1, 3).Offset(0, y - 1).value = discount / (margin - discount) End If Next Next End With Next End Sub