簡體   English   中英

VBA Excel Sub運行非常慢

[英]VBA Excel Sub runs really slow

我正在嘗試編寫此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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM