运行自动滚动宏,但有两个障碍

时间:2018-06-22 10:47:46

标签: excel vba excel-vba

我正在运行此宏,该宏将在指定的时间间隔自动滚动。我有两个问题:

  1. 当宏完成时,我希望它返回到工作表的顶部,但不是。

  2. 我希望它仅在指定的工作表上运行,而不是在整个工作簿上运行。

我的代码怎么了?

Sub ReRunMacro()
Dim xMin As String
    Dim lastRow As Long, i As Long
 Dim ws As Worksheet
 ws = ThisWorkbook.Worksheets("CNC Machining Cell 2", "CNC Grinding Cell", "CNC Turning Cell 1 & 3", "CNC Turning Cell 2")
lastRow = Range("A" & Rows.Count).End(xlUp).Row

For i = 1 To 14 Step 2
    Cells(i, 1).Select
    ActiveWindow.SmallScroll down:=1
    Application.Wait (Now + TimeValue("0:00:03"))
    If i = lastRow - 2 Or i = lastRow - 1 Then
        i = 0
        Cells(1, 1).Select
    End If
Next i
Debug.Print (i)
    xMin = GetSetting(AppName:="Kutools", Section:="Macro", Key:="min", Default:="")
    If (xMin = "") Or (xMin = "False") Then
      xMin = Application.InputBox(prompt:="Please input the interval time you need to repeat the Macro", Title:="Kutools for Excel", Type:=2)
      SaveSetting "Kutools", "Macro", "min", xMin
    End If
    If (xMin <> "") And (xMin <> False) Then

      Application.OnTime Now() + TimeValue("0:" + xMin + ":0"), "ReRunMacro"
    Else
      Exit Sub
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

在这里,我已经在代码注释中解释了它的工作原理

Sub ReRunMacro()

Dim xMin As String
Dim lastRow As Long, i As Long
Dim ws As Worksheet
Dim validSheets() As Variant

Set ws = ActiveSheet

' put the sheet names you want visible when the code is running into an array
validSheets = Array("CNC Machining Cell 2", "CNC Grinding Cell", "CNC Turning Cell 1 & 3", "CNC Turning Cell 2")

' check were on one of those sheets, if not exit (or pause the code, whatever you want to do
If UBound(Filter(validSheets, ws.Name)) = -1 Then ' we're not on the right sheet
    Exit Sub ' you can use the worksheet selection event to run this code again when the user moves to a different sheet
End If

lastRow = ws.Range("A100000").End(xlUp).Row ' it's best not to use row count, its unreliable, also you were going from the last row up and could land on row 1

For i = 1 To 14 Step 2
    ws.Cells(i, 1).Select ' always best to prefix a range with the worksheet it's on
    ActiveWindow.SmallScroll down:=1
    Application.Wait (Now + TimeValue("0:00:03"))
    If i = lastRow - 2 Or i = lastRow - 1 Then
        i = 0
        ws.Cells(1, 1).Select
    End If
Next i

xMin = GetSetting(AppName:="Kutools", Section:="Macro", Key:="min", Default:="")
If (xMin = "") Or (xMin = "False") Then
    xMin = Application.InputBox(prompt:="Please input the interval time you need to repeat the Macro", Title:="Kutools for Excel", Type:=2)
    SaveSetting "Kutools", "Macro", "min", xMin
End If

If (xMin <> "") And (xMin <> False) Then
    Application.OnTime Now() + TimeValue("0:" + xMin + ":0"), "ReRunMacro"
Else
    MsgBox "No values supplied, code will end", vbInformation ' it's polite to inform people you're stopping the code
    Exit Sub
End If

End Sub