我在此编码上遇到编译错误,无法弄清楚红色行有什么问题?
我已经搜索了几个站点以确定可能出了什么问题,但没有找到任何可以回答我的问题的内容?
Sub MsgBoxCritical()
Dim ws As Worksheet
Set ws = Worksheets("Travel Expense Form")
Dim amt As Range
Set amt = Range("U15:U45")
Dim proj As Range
Set proj = Range("N15:N45")
For Each Cell In ws("amt")
If Cell.Value > 0 Then
For Each Cell In ws("proj")
If Cell.Value = "" Then Cell.Interior.Color = vbRed
MsgBox "Project Number must be provided for all lines where
reimbursement is being requested" & vbCritical
Cancel = True
End If
End Sub
如果 U 列第 15-45 行中的任何单元格大于 0 并且相应行中 N 列中的单元格为空白,我希望在保存工作簿时显示此消息框。
我收到的编译错误在 Range U15:U45 的行上,是
Expected:Expression
错误?
最佳答案
编译错误意味着 VBA 无法编译代码。因此,它突出了“奇怪”的行。在这种情况下,两个 If 条件有点错误。这是写 And
的标准方式.它写成 1 如果:
Sub TestMe()
Dim conditionA As Boolean
Dim conditionB As Boolean
conditionA = True
conditionB = True
If conditionA And conditionB Then
MsgBox "Both true!"
End If
End Sub
关于代码,它有一些缺陷。一般来说,如果一个范围内的每个单元格都应该被检查,那么去循环并检查它。在某些情况下,也可以尝试
WorksheetFunction.Sum(Worksheets("Travel Expense Voucher").Range("U15:U45"))>0
,但很难获得行,在这种情况下高于 0。反正:Sub MsgBoxCriticalIcon()
Dim myCell As Range
With Worksheets("Travel Expense Voucher")
For Each myCell In .Range("U15:U45")
If myCell.Value > 0 And .Cells(myCell.Row, "N") = "" Then
MsgBox "Project must be ... at row " & myCell.Row
Exit Sub
End If
Next myCell
End With
End Sub
关于excel - 有人能告诉我我的 'MsgBox' 代码有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58784739/