Excel VBA从通过application.inputbox定义的范围返回单元格值

时间:2018-10-13 12:47:17

标签: excel vba

用户可以通过Application.InputBox方法选择一个范围。然后,我想检查该范围内第一个单元格中的值。

以下代码产生错误。有什么帮助吗?

Sub User_Range_Selection()
Dim xRg As Range

Set xRg = Application.InputBox("Please select a range:", "Range Selection", , , , , , 8)

MsgBox xRn.Cells(1, 1).Value
End Sub 

2 个答案:

答案 0 :(得分:1)

使用Option Explicit

退出子过程之前的最后一行代码将xRg更改为xRn。 Option Explicit将捕获该错误。

Option Explicit

Sub User_Range_Selection()

    Dim xRg As Range

    Set xRg = Application.InputBox("Please select a range:", "Range Selection", type:=8)

    MsgBox xRg.Cells(1, 1).Value

End Sub

答案 1 :(得分:0)

您可能想要添加错误处理,以防止用户输入但关闭窗体会暂停代码:

On Error Resume Next
Do
    Set xRg = Application.InputBox("Please select a range:", "Range Selection", , , , , , 8)
Loop While xRg Is Nothing
On Error GoTo 0

MsgBox xRg.Cells(1, 1).Value