有没有更简单的方法来编译此代码?

时间:2019-07-04 13:14:52

标签: excel vba

我有这个宏,可以将数据从一组单元格复制到另一张工作表。

我已经做到了,所以如果某些单元格为空,则会弹出一个文本框,必须在宏按钮接受并移动所有字段之前将其填充。

这里是:

If ActiveSheet.Range("A2") = "" Then
    MsgBox "Please Fill in More Boxes"
    Exit Sub
End If

If ActiveSheet.Range("B2") = "" Then
    MsgBox "Please Fill in More Boxes"
    Exit Sub
End If

If ActiveSheet.Range("C2") = "" Then
    MsgBox "Please Fill in More Boxes"
    Exit Sub
End If

然后从D2继续直到停止H2直到O2为止。

反正我可以编译它吗,所以它要短得多,而不是每个单元都多次编译?

我已经尝试过

If ActiveSheet.Range("A2:D2","H2:O2") = "" Then
    MsgBox "Please Fill in More Boxes"
    Exit Sub
End If

4 个答案:

答案 0 :(得分:2)

定义要测试的TestRange单元格范围,然后循环遍历该范围内的所有单元格:

Dim TestRange As Range
Set TestRange = ActiveSheet.Range("A2:D2") 'multiple ranges like "A2:D2,H2:O2"

Dim Cell As Range
For Each Cell In TestRange
    If Cell.Value = vbNullString Then
        MsgBox "Please Fill in More Boxes"
        Exit Sub
    End If
Next Cell

这将避免像

那样广泛使用Or
.Range("A2") = "" Or .Range("B2") = "" Or .Range("C2") = ""

答案 1 :(得分:2)

首先,您可以使用OR

If ActiveSheet.Range("A2") = "" Or ActiveSheet.Range("B2") = "" ... Then

但是您确实需要遍历范围

Dim c as Range
'For each c in ActiveSheet.Range("A2:D2","H2:O2").Cells (range incorrect)
 For each c in ActiveSheet.Range("A2:D2,H2:O2").Cells '(range corrected)
    If c="" Then 
       MsgBox "Please Fill in More Boxes" 
       Exit Sub 
    End If
Next

答案 2 :(得分:1)

您可以这样做:

With ActiveSheet
   If .Range("A2") = "" Or .Range("B2") = "" Or .Range("C2") = "" Then 
       MsgBox "Please Fill in More Boxes" 
     Exit Sub 
   End If
end With

以及其他单元格的类似区块

答案 3 :(得分:0)

您可以使用:

Option Explicit

Sub test()

    Dim rng As Range

    With ThisWorkbook.Worksheets("Sheet1") '<- Create a with statement with the sheet name you want. Avoid Activesheet
        'Set the range you want to check
        Set rng = .Range("A2:C2")
        'Loop rnage
        For Each cell In rng
            'If cell is empty
            If cell = "" Then
                'Message box with the cell which is missing
                MsgBox "Please Fill Box " & cell.Address
                Exit Sub
            End If
        Next cell

    End With

End Sub