使用input框作为excel范围
我想要用户input一个单元格的范围,如A1:Z26。 我试过添加引号,我已经尝试了2个input框,一个用于范围的开始和结束。 但是每次都出错:'object_global的方法范围失败'
我知道这是一个简单的语法问题(我认为),所以任何人都可以指出我在正确的方向,就如何让用户input一个范围,在set rng = range(msg)
Sub iterationLoop() Dim rng As Range, iteration As Range msg = "What is the range you'd like to look at: (eg 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
AADD
Dim rngstr as string
然后用inputbox使用这个:
rngstr = inputbox(msg) set rng = Range(rngstr)
Application.InputBox
允许你指定inputtypes。 types8对应于一个范围。 这将允许用户使用鼠标select范围或手动键入:
Sub test() Dim rng As Range Set rng = Application.InputBox("Select by mouse or enter (eg A1:B2) the range you'd like to look at:", Type:=8) MsgBox rng.Address End Sub
如果你打算让别人使用你的代码,你应该把Application.InputBox
调用包装在一些error handling代码中,因为如果用户按下Cancel
,上面的代码会产生运行时错误。 就像是:
On Error Resume Next Set rng = Application.InputBox("Select by mouse or enter (eg 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
(尽pipe你可能想要做一些更有用的事情,而不仅仅是放弃子)