gpt4 book ai didi

excel - 将输入框默认更改为当前输入

转载 作者:行者123 更新时间:2023-12-04 10:01:41 26 4
gpt4 key购买 nike

我正在尝试编写一个宏,它将输入框默认值重新设置为最后输入的值,因此如果我在下面的输入框中键入“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"
我怎样才能做到这一点?

最佳答案

  • 为了更好的可读性,我建议不要使用全大写变量名。
  • 我建议使用 Application.InputBox method而不仅仅是 InputBox因为在那里你可以指定 Type的输入。所以如果你设置Type:=1用户只能输入数字。
  • 确保您使用 Option Explicit强制正确的变量声明。我建议始终激活 Option Explicit : 在 VBA 编辑器中转到工具 › 选项 › Require Variable Declaration .

  • 一直持续到工作簿关闭……

    要使默认值在工作簿关闭之前保持不变,您需要将其声明为 Static (见 Static statement)。
    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

    请注意,如果您关闭并重新打开工作簿,它将以beeing 0 开头。再次。如果您希望它有所不同,您需要在您的 Static 之后添加类似以下内容的内容线:
    If RowsDown = 0 Then RowsDown = -1

    永远的坚持……

    当工作簿关闭时,变量无法保留值。如果即使工作簿关闭并重新打开,您也想让您的值(value)保持不变,那么您需要将其保存到(可能是隐藏的)工作表的单元格中。
    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

    关于excel - 将输入框默认更改为当前输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61786436/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com