[英]VBA Excel Sub runs really slow
I'm trying to write this Sub, which updates a table of a (known) certain amount of columns but a uncertain amount of rows. 我正在尝试编写此Sub,它更新了(已知)一定数量的列但不确定数量的行的表。 I have values in the last row of the table and in the first column of the table which i need for the calculation. 我在表的最后一行和表的第一列中有值,这些值是我需要进行计算的。 This is my code so far: (It works just runs really slow) 到目前为止,这是我的代码:(它的运行速度非常慢)
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
Help would be much appreciated 帮助将不胜感激
Try this, I've marked my comments with '//
and commented out your existing code with standard '
试试这个,我已经用'//
标记了我的注释,并用标准'
注释掉了你现有的代码'
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.