我已经构建了一个工具,它可以在宏运行时生成另一个电子表格。为了将该工作表成功上载到系统中,需要以特定的方式对其进行格式化。为了防止人们不正确地使用该工具并弄乱新电子表格上的格式,我构建了一系列检查。
每一个都检查一个单元格是否有一个特定的字符串(“请设置!”)如果是这样,弹出一个msgbox并停止宏。这个想法是,它通过每个检查,直到它命中一个失败,或者通过所有检查并运行代码来生成新的工作表。它现在有点冗长,我正在寻找一个循环来使它更整洁。
If Worksheets("Input").Range("F7").Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
Exit Sub
End If
If Worksheets("Input").Range("F9").Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
Exit Sub
End If
If Worksheets("Input").Range("F13").Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
Exit Sub
End If
If Worksheets("Input").Range("F17").Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
Exit Sub
End If
If Worksheets("Input").Range("F21").Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
Exit Sub
End If
If Worksheets("Input").Range("L9").Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
Exit Sub
End If
If Worksheets("Input").Range("L13").Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
Exit Sub
End If
If Worksheets("Input").Range("L17").Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
Exit Sub
End If
If Worksheets("Input").Range("L21").Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
Exit Sub
在这之后还有其他的代码来生成工作表。
一切都按预期运行,但上面的代码笨重得像地狱一样,我知道还有更好的方法。我研究过不同的循环,但我是VBA的新手,所以我不确定哪一个循环是最好的。任何帮助都是最好的!:)
发布于 2019-08-23 11:35:16
只需将要签入的地址放入一个数组中,然后遍历该数组以检查值。
Option Explicit
Public Sub ValidateFields()
Dim AddressesToCheck() As Variant
AddressesToCheck = Array("F7", "F9") 'add all addresses here
Dim Addr As Variant
For Each Addr In AddressesToCheck
If Worksheets("Input").Range(Addr).Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
Exit For
End If
Next Addr
End Sub
根据评论编辑:
要使main过程对ValidateFields
的结果做出反应,请将其转换为Function
而不是Sub
。
Option Explicit
Public Function IsFieldsValid() As Boolean
Dim AddressesToCheck() As Variant
AddressesToCheck = Array("F7", "F9") 'add all addresses here
IsFieldsValid = True 'set all fields valid until an invalid field is found.
Dim Addr As Variant
For Each Addr In AddressesToCheck
If Worksheets("Input").Range(Addr).Value = "Please Set!" Then
MsgBox "Please complete all the fields!", vbCritical
IsFieldsValid = False
Exit For
End If
Next Addr
End Function
因此,您可以使用结果对主过程进行反应,如…
Public Sub MainProcedure()
If IsFieldsValid Then '<< this will validate the fields and return `True` if they are all valid or `False` if one (or more) are not valid.
'do stuff if validation passed
Else
'do other stuff if one (or more) fields are not valid
Exit Sub 'for example abort main procedure
End If
End Sub
https://stackoverflow.com/questions/57625333
复制相似问题