[英]VBA user defined range and check if it is empty
I have been struggling with this for over an hour. 我已经为此奋斗了一个多小时。 I need to write a VBA code where the user selects a range and then I check if this selected range is empty before I go and do anything else.
我需要编写一个VBA代码,以便用户选择一个范围,然后在执行任何其他操作之前,请检查该选定范围是否为空。
This is what I have so far: 这是我到目前为止的内容:
Sub test()
Set rng= Application.InputBox("Select the range of the raw data please", Type:=8)
If Application.WorksheetFunction.CountA(Range(rng)) > 0 Then
MsgBox "do this, this and that!"
End If
End Sub
When I run this I get a "Method Range of object_Global failed". 运行此命令时,出现“ object_Global的方法范围失败”的信息。 I know it lets the user select the range just fine but the Range(rng) is not working right.
我知道它可以让用户选择合适的范围,但是Range(rng)不能正常工作。 Any help would be appreciated!
任何帮助,将不胜感激!
Your problem is that your variable rng
is a range and you're trying to wrap that in a range, which is why it's throwing an error. 您的问题是您的变量
rng
是一个范围,并且您试图将其包装在范围内,这就是为什么它会引发错误。 Try this instead. 试试这个吧。
Sub test()
Dim rng As Range
Set rng = Application.InputBox("Select the range of the raw data please", Type:=8)
If Application.WorksheetFunction.CountA(rng) > 0 Then
MsgBox "do this, this and that!"
End If
End Sub
Just some code 只是一些代码
Sub main()
Dim sentRange As Range
Set sentRange = Application.InputBox("Select the range of the raw data please", Type:=8)
If isRangeEmpty(sentRange) = False Then
MsgBox "Range is not empty."
Else
MsgBox "Good to go!"
End If
End Sub
Function isRangeEmpty(ByRef myRange As Range) As Boolean
Dim rngLoop As Range
Dim rangeEmpty As Boolean
For Each rngLoop In myRange
If rngLoop.Value = Empty Then
'All Good
isRangeEmpty = True
Else
'Need to exit
isRangeEmpty = False
Exit For
End If
Next rngLoop
End Function
If you are only acting on the instance of data being present then something like below will work. 如果仅对存在的数据实例进行操作,则类似下面的内容将起作用。 I would also adding
Option Explicit
to the top of your code and declare all variables. 我还将在代码顶部添加
Option Explicit
并声明所有变量。
Sub How()
Dim rng As Range
Set rng = Application.InputBox("Select Target Range", Type:=8)
If Application.WorksheetFunction.CountA(rng) <> 0 Then
'Actions
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.