将输入框的默认值改为当前输入

问题描述 投票:0回答:1

我试图编写一个宏,将输入框的默认值重新设置为最后输入的值,所以如果我在下面的输入框中输入 "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"

谁能帮助我如何实现这个问题?

excel vba excel-2007 inputbox
1个回答
2
投票
  1. 我建议不要使用全大写的变量名,以提高可读性。
  2. 我建议使用全大写的变量名,以提高可读性。Application.InputBox方法 而不是仅仅 InputBox 因为在那里你可以指定 Type 的输入。因此,如果你设置 Type:=1 用户只能输入数字。
  3. 确保你使用 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

0
投票

你需要定义全局变量,在这里你可以定义带有输入框的宏,例如:。

Private lastInput

Sub DefaultForInputBox()
    lastInput = InputBox("Enter some value", "InputBox", lastInput)
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.