我希望用户输入一系列单元格,例如 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
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
(虽然你可能想做一些比退出潜艇更有用的事情)
| 归档时间: | 
 | 
| 查看次数: | 995 次 | 
| 最近记录: |