【问题标题】:Excel VBA LoopingExcel VBA循环
【发布时间】:2017-05-26 18:25:28
【问题描述】:

好吧,请耐心等待,我对 Excel 中的 VBA 很陌生。几天来,我一直试图弄清楚如何循环输入我为错误检查而制作的时间表,我只是傻眼了。

我的时间表看起来像这样

所以我一直试图让一个循环来寻找空单元格。

我的范围是 ("C4:I4") 并且我需要在从 C4 开始的 29 行上运行它。

  • 如果某一行在该范围内的每个单元格中都有数据,那么我希望将它发送到GoTo 500
  • 如果一行有任何单元格中的数据但未全部填写,我需要它显示一个MsgBox 来告诉用户需要填写什么。
  • 如果除第一个之外的一行中的整个范围为空,那么我需要GoTo 500 来运行代码的保存文件部分。

任何帮助将不胜感激。我浏览了论坛并试图让多个循环示例为我工作,但一直无法做到。

Sub checkemptycells()

    Dim x As String

    Range("C1").Select
    If ActiveCell.Text = "" Then
        MsgBox "Pick Your Name"
        GoTo 1000
    End If

    Range("G1").Select
    If ActiveCell.Text = "" Then
        MsgBox "ENTER A DATE"
        GoTo 1000
    End If

    Range("C4").Select
    If ActiveCell.Text = "" Then
        MsgBox "Need Job#"
        GoTo 1000
    End If

    Range("D4").Select
    If ActiveCell.Text = "" Then
        MsgBox "need qty."
        GoTo 1000
    End If

    Range("E4").Select
    If ActiveCell.Text = "" Then
        MsgBox "Need Work Order!"
        GoTo 1000
    End If

    Range("F4").Select
    If ActiveCell.Text = "" Then
        MsgBox "Pick a Dept.!"
        GoTo 1000
    End If

    Range("G4:I4").Select
    If ActiveCell.Text = "" Then
        MsgBox "Fill Start & Stop times on this line"
        GoTo 1000
    End If

    Dim FilePath As String
    Dim FileName As String
    Dim MyDate As String
    Dim USER As String

    FilePath = "Z:\TIMESHEETS\"
    MyDate = Format(Now(), "mm_dd_yyyy_")
    USER = (ActiveSheet.Range("  C1"))

    FileName = FilePath & MyDate & USER
    ActiveWorkbook.SaveAs FileName:=FileName, FileFormat:=xlWorkbookNormal
    ActiveWorkbook.Close
    OpenAfterPublish = False
    xls.DisplayAlerts = False

1000
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    这样的东西有用吗?

    Dim i as Variant
    Dim j as Variant
    
    For i = 4 to 32
    For j = 3 to 9
    
        If Cells(i,j).Value="" Then
    
        MsgBox "Missing value in Cell(" & i & " ," & j & ")."
    
        End If
    
    Next j
    Next i
    

    【讨论】:

    • 先声明范围然后使用单个 For Each 循环而不是嵌套循环可能更有意义。
    • @J_Lard 我尝试将 Dim Rng 设置为 Range,Rng = Range("C4:I32"),然后仍然发现自己在嵌套循环。相比之下,这似乎更容易。如果我做错了,那为什么思考起来很痛苦也是有道理的……
    • 你可以说Set rng = Range("C4:I32"),然后是For Each c in rng... If c.Value = ""...。无论哪种方式都应该有效:)
    • 明白了!感谢您下次提供的提示...我自己对循环还是很陌生。迄今为止,我得到了很多帮助才能到达我所在的位置。
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2012-05-30
    • 2015-08-03
    相关资源
    最近更新 更多