【问题标题】:Have macro for loop, need to throttle and only move to next i when a new button is pressed有宏循环,需要油门,只有在按下新按钮时才移动到下一个 i
【发布时间】:2013-04-16 19:28:05
【问题描述】:

我几乎有一个想要运行的循环,但是我不希望它进入下一个“i”,直到按下按钮。我的代码如下。我相信我的问题是“If GoGo”的位置,但我在很多地方都试过了。

Sub GoGo()
    Public GoGo As Boolean
    GoGo = True
End Sub

Sub Runn()
    Dim lastrow As Long, i As Long

    For i = 23 To 32
        DoEvents
        If GoGo = True Then
            If Cells(i, 1) <> 0 Then
                 Range("B5").Value = Cells(i, 2).Value
                 Range("E5").Value = Cells(i, 3).Value
                 Range("E11").Value = Range("C33").Value
                 Application.Run ("Realcount")
                 Application.Run ("Realcount2")
            End If
        End If
    Next i
End Sub

【问题讨论】:

标签: excel vba


【解决方案1】:

这是你正在尝试的吗?

Public GoGo As Boolean

Sub GoGoProc()
    GoGo = True
End Sub

Sub Runn()
    Dim lastrow As Long, i As Long

    i = 23

    Do
        DoEvents
        If GoGo = True Then
            If Cells(i, 1) <> 0 Then
                Range("B5").Value = Cells(i, 2).Value
                Range("E5").Value = Cells(i, 3).Value
                Range("E11").Value = Range("C33").Value
                Application.Run ("Realcount")
                Application.Run ("Realcount2")
            End If
            i = i + 1
            GoGo = False
        End If
    Loop
End Sub

跟进(来自评论)

我能想到的最好方法不是使用循环,而是使用无模式用户表单(这样您就可以同时使用Workbook/Worksheet)和Next 按钮. Next 按钮将增加行值,然后运行代码。这样,如果您不得不离开去喝杯咖啡,您就不会让 Excel 忙碌;)

创建应如下所示的用户表单(未测试)

将此代码粘贴到用户表单中

'~~> Next Button
Private Sub CommandButton1_Click()
    Range("B5").Value = Cells(rw, 2).Value
    Range("E5").Value = Cells(rw, 3).Value
    Range("E11").Value = Range("C33").Value

    Application.Run ("Realcount")
    Application.Run ("Realcount2")

    rw = rw + 1
End Sub

'~~> Canecel Button
Private Sub CommandButton2_Click()
    Unload Me
End Sub

创建一个模块并将此代码粘贴到那里

Public rw As Long

Sub Launch()
    rw = 23
    UserForm1.Show vbModeless
End Sub

要运行您的代码,您可以直接运行 Sub Launch() 或在您的工作表上创建一个命令按钮(表单控件 - 我猜这是您正在使用的)并将 Sub Launch() 分配给它。

【讨论】:

  • 它一直在说“模棱两可的名字”。代码看起来不错,但我无法测试它!我会尝试谷歌这意味着什么..
  • 如果您以前使用过该名称,似乎会出现这种情况,但我尝试了不同的随机词,没有运气。
  • 看起来更好,所以你建议我设置一个链接到 GoGoProc() 宏的按钮,然后为每个 i 单击它。你也给了我们很大的帮助。
  • 除了循环之外,您是否考虑过使用用户表单通过NEXT 按钮运行宏?这样你就不会让 Excel 忙于你的 Do Loop 想象一下,如果你不得不去喝杯咖啡?
  • 发布更新。刷新页面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 2023-02-10
  • 1970-01-01
相关资源
最近更新 更多