如何显示错误消息并停止宏

问题描述 投票:1回答:2

我是编码VBA的新手。我想添加一个弹出框,其中显示消息“今天的日期未找到”,如果在K列中找不到今天的日期,则停止宏。不确定如何进行此操作以及代码应该在何处。

' Find the last row on the count sheet and the next row on the archieve sheet

lastRow = countSheet.Cells(countSheet.Rows.count, "K").End(xlUp).Row
nextRow = archieveSheet.Cells(countSheet.Rows.count, "K").End(xlUp).Row + 1

' Look at all rows in the count sheet
For thisRow = 1 To lastRow

    ' Check if column K contains today's date
    If countSheet.Cells(thisRow, "K").Value = Date Then

        ' Copy the entire row to the archieve sheet
        countSheet.Cells(thisRow, "K").EntireRow.Copy Destination:=archieveSheet.Cells(nextRow, "A")

        ' Move to the next row on the archieve sheet
        nextRow = nextRow + 1
    End If
Next thisRow
excel vba
2个回答
5
投票

在开头添加一些简单的代码将使一切变得简单

If Application.WorksheetFunction.CountIf(countsheet.Range("K:K"), Date) = 0 Then
    MsgBox "Today's Date Not Found"
    Exit Sub
End If

0
投票

这样的事情对你有用:

'Create a new boolean variable for keeping track of if the date has been found
Dim bDateFound As Boolean

'Set that boolean to false to begin with (this step is optional, it will be False by default if not defined)
bDateFound = False
lastRow = countSheet.Cells(countSheet.Rows.Count, "K").End(xlUp).Row
nextRow = archieveSheet.Cells(countSheet.Rows.Count, "K").End(xlUp).Row + 1

' Look at all rows in the count sheet
For thisRow = 1 To lastRow

    ' Check if column K contains today's date
    If countSheet.Cells(thisRow, "K").Value = Date Then
        'Add line here because a date was found to set your boolean variable to true
        bDateFound = True

        ' Copy the entire row to the archieve sheet
        countSheet.Cells(thisRow, "K").EntireRow.Copy Destination:=archieveSheet.Cells(nextRow, "A")

        ' Move to the next row on the archieve sheet
        nextRow = nextRow + 1
    End If
Next thisRow

'After your loop, put in a check to see if the date was found
If bDateFound = False Then
    'If the boolean is still false, then it was never found
    'Display a msgbox containing your error
    MsgBox "Today's date not found. Exiting macro.", , "Error"
    Exit Sub    'Exit the macro
End If

'If the date was found, then the code will continue here
© www.soinside.com 2019 - 2024. All rights reserved.