使用inputbox作为excel范围

时间:2015-09-04 15:30:40

标签: excel vba excel-vba

我希望用户输入一系列单元格,例如A1:Z26。我尝试过添加引文,我尝试过有2个输入框,一个用于范围的开头和结尾。但它每次都会出错:< object_global的方法范围失败'

我知道这是一个简单的语法问题(我认为)所以任何人都可以指出我在如何让用户输入适用于set rng = range(msg)

的范围方面的正确方向
Sub iterationLoop()

Dim rng As Range, iteration As Range

msg = "What is the range you'd like to look at: (e.g. A1:B2)"
InputBox (msg)
Set rng = Range(msg)

For Each iteration In rng
iteration.Select
If iteration = vbNullString Then
iteration = "add value"
MsgBox ("Cell: " & Selection.Address & " has no value")
End If

Next

End Sub

2 个答案:

答案 0 :(得分:4)

Application.InputBox允许您指定输入类型。类型8对应于范围。这将允许用户使用鼠标选择范围或手动输入:

Sub test()
    Dim rng As Range
    Set rng = Application.InputBox("Select by mouse or enter (e.g. A1:B2) the range you'd like to look at:", Type:=8)
    MsgBox rng.Address
End Sub

如果您打算让其他人使用您的代码,您应该将Application.InputBox调用包装在一些错误处理代码中,因为如果用户按下Cancel,上面的代码会引发运行时错误。类似的东西:

On Error Resume Next
    Set rng = Application.InputBox("Select by mouse or enter (e.g. A1:B2) the range you'd like to look at:", Type:=8)
    If Err.Number > 0 Then
        MsgBox "No Range Selected"
        Exit Sub
    End If
On Error GoTo 0

(尽管你可能想做一些比退出sub更有用的东西)

答案 1 :(得分:3)

AADD

Dim rngstr as string

然后使用输入框使用:

rngstr = inputbox(msg)
set rng = Range(rngstr)
相关问题