2013-07-03 30 views
2

我有這個函數根據左側單元格的值更新單元格。 不幸的是,我不得不在函數結束之前添加最後一行代碼,這樣工作表就會回滾,因爲當我點擊按鈕來運行宏時,每個單元格都會被選中,從而向下滾動到最後一行數據(600行)。如何停止Excel中的單元格滾動vba

如果你能告訴我該怎麼做才能避免這種情況,那將非常感激。

的代碼是:

Sub Button2_Click() 
Dim regExM As New RegExp 
Dim regEx As New RegExp 
Dim matches, level 

regExM.Pattern = "(M)(\d)" 
regEx.Pattern = "[^-](.{0})(\d)" 
regExM.Global = False 

    Range("J2").Activate 
    ' Set Do loop to stop when an empty cell is reached. 
    Do Until IsEmpty(ActiveCell) 
    If regExM.Test(ActiveCell.Value) Then 
     Set matches = regExM.Execute(ActiveCell.Value) 
     For Each Match In matches 
      level = matches(0).SubMatches(1) + 3 
      ActiveCell.Offset(0, 1).Value = level 
     Next 
    ElseIf regEx.Test(ActiveCell.Value) Then 
     Set matches = regEx.Execute(ActiveCell.Value) 
     For Each Match In matches 
      level = matches(0).SubMatches(1) 
      ActiveCell.Offset(0, 1).Value = level 
     Next 
    End If 
    ' Step down 1 row from present location. 
    ActiveCell.Offset(1, 0).Activate 
    Loop 
    Range("A1").Select 
End Sub 

謝謝

回答

2

您可以在宏運行時關閉屏幕更新。

Sub Button2_Click() 
Application.ScreenUpdating = False 
'...code 
    Range("A1").Select 
Application.ScreenUpdating = True 
End Sub 
+1

謝謝你,我會用你的解決方案,但我也從前面的招貼畫的反應中學到了一些東西。 – Crouzilles

3

我不認爲有必要以激活細胞。只需循環遍歷該範圍並根據值執行所需操作。這應該會更快,並避免在運行時移動紙張。

Option Explicit 

Sub Button2_Click() 
Dim regExM As New RegExp 
Dim regEx As New RegExp 
Dim matches, level 
Dim lr As Long 
Dim i As Long 

With Application 
    .ScreenUpdating = False 
    .Calculation = xlCalculationManual 
End With 


lr = ActiveSheet.UsedRange.Rows.Count 

regExM.Pattern = "(M)(\d)" 
regEx.Pattern = "[^-](.{0})(\d)" 
regExM.Global = False 


    For i = 2 To lr 
    If regExM.Test(Range("J" & i).Value) Then 
     Set matches = regExM.Execute(Range("J" & i).Value) 
     For Each Match In matches 
      level = matches(0).SubMatches(1) + 3 
      Range("J" & i).Offset(0, 1).Value = level 
     Next 
    ElseIf regEx.Test(Range("J" & i).Value) Then 
     Set matches = regEx.Execute(Range("J" & i).Value) 
     For Each Match In matches 
      level = matches(0).SubMatches(1) 
      Range("J" & i).Offset(0, 1).Value = level 
     Next 
    End If 
    Next i 

With Application 
    .ScreenUpdating = True 
    .Calculation = xlCalculationAutomatic 
End With 
End Sub