如何解决如何在 VBA 用户窗体中处理 RefEdit 控件的空白/无效数据或如何在 VBA 中检查 Range() 是否有效/不错误
我正在使用 Excel VBA 用户表单来更改字体大小写,如下图所示。当 RefEdit 控件具有正确的范围时,它就可以正常工作。但是,如果我单击“应用”按钮使 RefEdit 保持空白/只有空格/任何单词(无效范围),用户表单就会消失而不显示任何错误通知。
对于大写代码:-
Sub UpperCaseFont()
For Each x In Range(CaseRefEdit.Value)
If Not IsEmpty(x.Value) Then
x.Value = UCase(x.Value)
End If
Next
MsgBox "Done"
End Sub
小写代码:-
Sub LowerCaseFont()
For Each x In Range(CaseRefEdit.Value)
If Not IsEmpty(x.Value) Then
x.Value = LCase(x.Value)
End If
Next
MsgBox "Done"
End Sub
正确的代码:-
Sub ProperCaseFont()
For Each x In Range(CaseRefEdit.Value)
If Not IsEmpty(x.Value) Then
x.Value = WorksheetFunction.Proper(x.Value)
End If
Next
End Sub
命令按钮代码:-
Private Sub CaseApplyCommandButton_Click()
If UpperCase = True Then Call UpperCaseFont
If LowerCase = True Then Call LowerCaseFont
If ProperCase = True Then Call ProperCaseFont
出于这个原因,我试图修改如下,但我仍然面临的问题是,如果RefEdit为空,我点击“应用”按钮然后用户表单消失,还发现其他所有用户表单启动未知问题进行初始化.
Private Sub CaseApplyCommandButton_Click()
'Font Case
Dim Rng As Range
On Error Resume Next
Set Rng = Range(Me.CaseRefEdit.Value)
MsgBox Rng
On Error GoTo 0
If Rng Is Nothing Then
MsgBox "Select the Cells to change the case"
Else
If UpperCase = True Then Call UpperCaseFont
If LowerCase = True Then Call LowerCaseFont
If ProperCase = True Then Call ProperCaseFont
End If
End Sub
我发现添加以下代码时问题开始了:-
Private Sub CaseRefEdit_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Range(CaseRefEdit.Value).Select
End Sub
根据我的理解,当 RefEdit 没有为输入任何数字或单词提供任何范围或保持空白时,用户表单就会消失。有什么解决办法吗?
解决方法
关于第二个问题。 [if IsError(range("Hello") then ...] 表达式首先对range("Hello")求值,如果无效则报错在调用函数之前。因此,最好将范围的地址传递给 IsError 函数,并在函数内部计算范围并确定其正确性。
Function IsError(addr As String) As Boolean
Dim rng As Range
On Error Resume Next
Set rng = Range(addr)
IsError = rng Is Nothing
End Function
Sub test1()
If IsError("%$%W34") Then
Debug.Print "Range is invalid"
Else
Debug.Print "Range is correct"
End If
End Sub
,
您可以使用 On Error 语句,例如:
Function testRNG(addr As String) As Range ' returns correct Range object or Nothing otherwise
' initially testRNG = Nothing
On Error Resume Next
Set testRNG = Range(addr) ' if the address is correct,testRNG returns Range,otherwise an error occurs,the expression is not evaluated and testRNG remains Nothing
End Function
Sub foo()
Dim addr As String
addr = "W12"
Set Rng = testRNG(addr)
If Rng Is Nothing Then
Debug.Print "Address " & addr & " is wrong"
Else
Debug.Print "Range " & Rng.Address & " is correct"
End If
End Sub
,
我的问题解决如下。谢谢@Алексей Р。
Private Sub CaseRefEdit_Exit(ByVal Cancel As MSForms.ReturnBoolean)
On error resume next
Range(CaseRefEdit.Value).Select
End Sub
有谁知道,如何检查 Range("etc")/ Range(123) 是否有效?喜欢-
If IsError(range("etc")) then
...
else
....
end if
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。