我是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
答案 0 :(得分:5)
在开头添加一些简单的代码将使一切保持简单
If Application.WorksheetFunction.CountIf(countsheet.Range("K:K"), Date) = 0 Then
MsgBox "Today's Date Not Found"
Exit Sub
End If
答案 1 :(得分: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