使用If语句使用VBA复制单元格

时间:2013-07-25 10:08:20

标签: vba excel-vba if-statement for-loop boolean

我是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

1 个答案:

答案 0 :(得分:0)

欢迎使用 stackoverflow.com

您必须使用 copy code block for 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