我试图编写一个宏,将输入框的默认值重新设置为最后输入的值,所以如果我在下面的输入框中输入 "2",下次运行宏时,默认值将变为2。
只有等到我运行该宏的工作簿关闭后,才能恢复原来的默认值
(Excel 2007)
ROWSDOWN = InputBox("enter no.of rows DOWN to move the cells", "VerticalMove", _
-1) 'default -1 (=1 row up)
我试过设置 PREV_ROWSDOWN = ROWSDOWN
但我的尝试(如下图)并不成功:下次运行宏时,输入框默认为0,宏结束后PREV_ROWSDOWN(和ROWSDOWN)的值就会丢失?
ROWSDOWN = InputBox("enter no.of rows DOWN to move the cells (0=no change, - =move UP)", "VerticalMove", _
PREV_ROWSDOWN) 'should set default as value entered last time the macro run
PREV_ROWSDOWN = ROWSDOWN ''NW-not saved after macro finished, default changed to "0"
谁能帮助我如何实现这个问题?
InputBox
因为在那里你可以指定 Type
的输入。因此,如果你设置 Type:=1
用户只能输入数字。Option Explicit
来强制执行正确的变量声明。我建议总是激活 Option Explicit
: 在VBA编辑器中,进入 工具类 › 选项 › 要求变量声明.要使你的默认值持久化,直到工作簿关闭,你需要把它声明为 Static
(见 静态声明).
Option Explicit
Public Sub Test()
Static RowsDown As Long 'Static variables will keep the value until next call
RowsDown = Application.InputBox(Prompt:="enter no.of rows DOWN to move the cells (0=no change, - =move UP)", Title:="VerticalMove", Default:=RowsDown, Type:=1)
End Sub
请注意,如果您关闭并重新打开您的工作簿,它将从您的工作簿开始。0
再次。如果你想让它变得不一样,你需要在你的 Static
行。
If RowsDown = 0 Then RowsDown = -1
当工作簿关闭时,变量不能保留值。如果你想让你的值在工作簿关闭和重新打开时也能保持不变,那么你需要把它保存到一个(可能是隐藏的)工作表的单元格中。
Option Explicit
Public Sub Test()
Dim RowsDown As Long
RowsDown = Application.InputBox(Prompt:="enter no.of rows DOWN to move the cells (0=no change, - =move UP)", Title:="VerticalMove", Default:=ThisWorkbook.Worksheets("hiddensheet").Range("A1").Value, Type:=1)
ThisWorkbook.Worksheets("hiddensheet").Range("A1").Value = RowsDown
End Sub
你需要定义全局变量,在这里你可以定义带有输入框的宏,例如:。
Private lastInput
Sub DefaultForInputBox()
lastInput = InputBox("Enter some value", "InputBox", lastInput)
End Sub