excel - 有人能告诉我我的 'MsgBox' 代码有什么问题吗?

标签 excel vba

我在此编码上遇到编译错误,无法弄清楚红色行有什么问题?

我已经搜索了几个站点以确定可能出了什么问题,但没有找到任何可以回答我的问题的内容?

    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/

相关文章:

sql - 从Excel工作表生成sql插入脚本

vba - 命名范围字符串限制

vba - 通过 COM 创建 TimeSpan 实例

excel - 如何将输出、MsgBox 结果放在新列上

VBA循环遍历一个列,获取每个位置的前10个(如果小于10,则为最大值)的范围

vba - 文件系统对象后期绑定(bind)

vba - 无需打开工作簿即可访问内置文档属性信息

sql-server - 使用 SSIS 导入空白 Excel 列

vba - 循环工作表时对象定义错误

vba - 如何在文本框中设置密码错误的注销?