我有一个存储为字符串的范围变量。我只是想检查给定的范围是否有效。例如:
A11:Z4, D8:H7, B112:H80, M5:P45
无效、A5:A5
无效(一种情况)、A11:Z11, D8:H8, A5:M5
有效。我只想进入同一行不同的列。
我们怎样才能做到这一点?
如果您在 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
这里有一些您可以使用的代码:
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
感谢您的帮助。我只是使用下面的方法来解决这个问题。
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
Function IsVal(iAdd As String) As Boolean
'if iAdd is specified above Cell Level, it must exist in an Open Workbook
' eg "[Book1.xls]Sheet1!A11:Z4"
Dim zRa As Range
On Error Resume Next
Set pZ.Ra = Evaluate(iAdd)
IsVal = Err.Number = 0
Err.Clear
End Function