【问题标题】:VBA If Then statement to do stuff or end subVBA If Then 语句做事或结束子
【发布时间】:2018-11-29 18:12:44
【问题描述】:

我无法编写简单的代码。我想添加If Then语句,如果满足条件(单元格值不是1或7),则执行代码块,否则结束子。代码块包括登录网站和 2 For Next 循环。基本上宏是在工作日运行,如果是周六或周日则不运行。感谢您的帮助。

这是一个测试代码:

Sub test()

Dim i As Integer

'If cell E1 has a value of neither 1 or 7, Do stuff, otherwise End the Sub

If Cells(5, 1) <> 1 Or Cells(5, 1) <> 7 Then

    'Do stuff includes login and perform 2 For Next loops in my real code 
    For i = 1 To 3
        Cells(i, 1).Value = Cells(i, 1).Value * 2
    Next

End If

End Sub

【问题讨论】:

  • Or改成And
  • 您是否在循环之前编写了 if cells(5,1)=1 或 cells(5,1)=7 then exit sub,这将解决同样的问题。它将消除对代码末尾的 end if 块的需要。根据“做事”的长度,从长远来看,这种方式可能会更干净
  • Cells(5, 1) 是 A5 而不是 E1
  • 为什么要检查表格? VBA 有一个用于检查星期几的内置函数:If Weekday(Date, vbMonday) &gt; 5 Then
  • 感谢所有提示。我意识到我的单元格错误为 A5,我将查看 vba 函数以检查星期几...谢谢大家。

标签: excel vba


【解决方案1】:

试试

Sub test()

    Dim i As Integer

    'If cell E1 has a value of neither 1 or 7, Do stuff, otherwise End the Sub

    If Cells(5, 1) = 1 Or Cells(5, 1) = 7 Then
    Else
        'Do stuff includes login and perform 2 For Next loops in my real code
        For i = 1 To 3
            Cells(i, 1).Value = Cells(i, 1).Value * 2
        Next

    End If

End Sub

【讨论】:

    【解决方案2】:

    我终于能够实现我想要的。我创建了一个新的子来检查星期几,如果是星期六或星期日然后退出子,否则调用我拥有的原始子,它工作得很好。但是,正如共产国际建议的那样,我将研究检查日期的 VBA 功能,而不是使用电子表格。谢谢大家。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多