1

我是 VBA 的初学者,我想知道如何在我的代码中添加 IF ELSE 语句:我只想在单元格已填充且未填充时启用复制单元格 msgbox 必须弹出

代码:

Private Sub CommandButton3_Click()

 Application.ScreenUpdating = False

    Dim NextRow As Range

    Sheet1.Range("F7,F10,F13,F16,F19,F22,F25,F28").Copy

    Sheets("Overzicht").Select
    Set NextRow = ActiveSheet.Cells(Cells.Rows.Count, 1).End(xlUp).Offset(1, 0)
    NextRow.Select
    Selection.PasteSpecial (xlValues), Transpose:=True

    MsgBox "Invoer is opgeslagen"

    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub
4

1 回答 1

0

欢迎来到stackoverflow.com

您必须copy code blockfor loop,IF-ELSE语句和Boolean类型变量包装您的。

首先,您要遍历指定的单元格范围并确保它们都已填充

 Dim allFilled As Boolean
    Dim i As Long
    For i = 7 To 28 Step 3
        If Not IsEmpty(Sheet1.Range("F" & i)) Then
            allFilled = True
        Else
            allFilled = False
        End If
    Next i

如果是,您可以继续复制粘贴,如果不是,程序将显示一个消息框:Not all the cells are filled! Cant copy

你的完整代码:

Sub CommandButton3_Click()
 Application.ScreenUpdating = False

    Dim allFilled As Boolean
    Dim i As Long
    For i = 7 To 28 Step 3
        If Not IsEmpty(Sheet1.Range("F" & i)) Then
            allFilled = True
        Else
            allFilled = False
        End If
    Next i

    If allFilled Then ' = if (allFilled = true) then
        Dim NextRow As Range
        Sheet1.Range("F7,F10,F13,F16,F19,F22,F25,F28").Copy

        Sheets("Overzicht").Select
        Set NextRow = ActiveSheet.Cells(Cells.Rows.Count, 1).End(xlUp). _ 
                      Offset(1, 0)
        NextRow.Select
        Selection.PasteSpecial (xlValues), Transpose:=True

        MsgBox "Invoer is opgeslagen"

        Application.CutCopyMode = False
        Application.ScreenUpdating = True
    Else
        MsgBox "Not all the cells are filled! Cant copy"
    End If
End Sub

Update来自评论

是的,也可以单独执行不同的检查,例如:

Dim allFilled As Boolean
If Not IsEmpty(Range("F7, F10, F13, F16")) And IsEmpty(Range("F8")) Then
    ' F7, F10, F13, F16 are not empty and F8 is empty
    allFilled = True
ElseIf IsEmpty(Range("F28")) Then
    ' F28 empty cannot execute copy-paste
    allFilled = False
Else
    allFilled = False
End If
于 2013-07-25T10:44:30.997 回答