excel 我可以在MsgBox中打印范围和文本吗?

ifmq2ha2  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(157)

我正在Excel上写一个宏。
每次在特定范围内键入值时,如果计算结果过低,我需要出现一个消息框,显示“样品体积过低!请增加总体积”,并打印键入的范围。
下面的代码只打印消息,但我需要知道我是否也可以打印范围。
谢谢你

Private Sub Worksheet_Change(ByVal Target As Range)

Dim r1 As Range, r2 As Range, MultipleRange As Range
Set r1 = Range("I17:I20")
Set r2 = Range("Q17:Q20")
Set MultipleRange = Union(r1, r2)

If Not Intersect(Target, MultipleRange) Is Nothing Then

 If Range("G17") < 5 Then
        MsgBox "Sample volume too low!Please increase total volume."
    End If
If Range("G18") < 5 Then
        MsgBox "Sample volume too low! Please increase total volume."
    End If
If Range("G19") < 5 Then
        MsgBox "Sample volume too low! Please increase total volume."
    End If
If Range("G20") < 5 Then
        MsgBox "Sample volume too low! Please increase total volume."
If Range("O17") < 5 Then
        MsgBox "Sample volume too low! Please increase total volume."
    End If
If Range("O18") < 5 Then
        MsgBox "Sample volume too low! Please increase total volume."
    End If
If Range("O19") < 5 Then
        MsgBox "Sample volume too low! Please increase total volume."
    End If
If Range("O20") < 5 Then
        MsgBox "Sample volume too low! Please increase total volume."
    End If

End If

End Sub
n6lpvg4x

n6lpvg4x1#

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)

    Dim r1 As Range, r2 As Range, MultipleRange As Range
    Dim msg As String, c, r as long
    
    Set r1 = Range("I17:I20")
    Set r2 = Range("Q17:Q20")
    Set MultipleRange = Union(r1, r2)
    
    If Intersect(Target, MultipleRange) Is Nothing Then Exit Sub
    
    For Each c In Array("G", "O")
        For r = 17 To 20
            If Cells(r, c) < 5 Then
                msg = msg & vbLf & "Cell " & c & r
            End If
        Next
    Next
    
    If Len(msg) > 0 Then
        MsgBox "Sample volume too low! Please increase total volume in cells " & msg, vbExclamation
    End If

End Sub

相关问题