如果给定范围有效,请与VBA核实

时间:2017-10-09 07:10:25

标签: excel vba excel-vba range

我有一个范围变量存储为字符串。我只是检查给定的范围是否有效。例如:A11:Z4, D8:H7, B112:H80, M5:P45无效,A5:A5无效(一种情况),A11:Z11, D8:H8, A5:M5有效。我只是想进入同一行,不同的列。

我们怎么做?

3 个答案:

答案 0 :(得分:2)

以下是您可以使用的一些代码:

Sub Validate()
Dim rng As String
'here you can define your range
rng = "C11:D12"

If Range(rng).Rows.Count = 1 And Range(rng).Columns.Count > 1 And Range(rng).Areas.Count = 1 Then
    MsgBox "Range is valid"
Else
    MsgBox "Range is invalid"
End If

End Sub

答案 1 :(得分:2)

如果在VBA中打印出Range对象的地址,它将按正确的顺序打印地址。因此,如果您通过A6:A5,它就会知道您实际上是指A5:A6

您可以使用它来创建UDF:

修改

我误解了这个问题。所以,我修改了我的答案以纠正错误。

注意:这基本上是Michal Turczyn的答案,以UDF的形式重写:

Function IS_RANGE_VALID(s As String) As Boolean
    IS_RANGE_VALID = (Range(s).Rows.Count = 1 And Range(s).Columns.Count > 1)
End Function

结果:

╔═══╦══════════╦═══════╗
║   ║    A     ║   B   ║
╠═══╬══════════╬═══════╣
║ 1 ║ A11:Z4   ║ FALSE ║
║ 2 ║ D8:H7    ║ FALSE ║
║ 3 ║ B112:H80 ║ FALSE ║
║ 4 ║ M5:P45   ║ FALSE ║
║ 5 ║ A5:A5    ║ FALSE ║
║ 6 ║ A11:Z11  ║ TRUE  ║
║ 7 ║ D8:H8    ║ TRUE  ║
║ 8 ║ A5:M5    ║ TRUE  ║
╚═══╩══════════╩═══════╝

注意:就像我在评论中问你一样,为什么M5:P45无效?如果这是一个错字,那么这应该适合你。否则,您必须更清楚地了解您用来确定范围有效性的标准。​​

答案 2 :(得分:0)

感谢您的帮助。我只是用下面的方法来解决这个问题。

                Dim i As Integer
                Dim retval As String
                Dim retval1 As String
                Dim colFrom As String
                Dim colTo As String

        'Example : FromRange = A5, ToRange =D5
                If FromRange = ToRange  Then  'For Same Column
                    MsgBox "The Input Range specified is invalid"
                    Exit Sub
                End If

                colFrom = FromRange 
                colTo = ToRange  
        'Get the numbers only from given range and compare it
                For i = 1 To Len(colFrom)
                    If Mid(colFrom, i, 1) >= "0" And Mid(colFrom, i, 1) <= "9" Then
                        retval = retval + Mid(colFrom, i, 1)
                    End If
                Next

                For i = 1 To Len(colTo)
                    If Mid(colTo, i, 1) >= "0" And Mid(colTo, i, 1) <= "9" Then
                        retval1 = retval1 + Mid(colTo, i, 1)
                    End If
                Next

                If retval <> "" And retval1 <> "" And retval = retval1 Then
                    myCellRange= FromRange  & ":" & ToRange  
                Else
                    MsgBox "Input Range is invalid"
                    Exit Sub
                End If