2015-09-04 92 views
0

我希望用户输入一系列单元格,如A1:Z26。我试过添加引号,我已经尝试了2个输入框,一个用于范围的开始和结束。但它错误每次与:'object_global的方法范围失败'使用输入框作为excel范围

我知道这是一个简单的语法问题(我认为),所以任何人都可以指出我在正确的方向就如何让用户输入一个范围在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 

回答

3

AADD

Dim rngstr as string 

作品然后与输入框使用:

rngstr = inputbox(msg) 
set rng = Range(rngstr) 
+0

干得好,斯科特。作品。谢谢。 –

+0

@JosephErickson很高兴我能帮到 –

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 

(尽管你可能想要做的东西不仅仅是退出子更有用)

+0

这比使用Inputbox好得多。值得考虑添加'Selection.Address'作为默认地址 – brettdj