【问题标题】:Excel VBA userform - using the same form to generate continuous dataExcel VBA用户表单——使用同一个表单生成连续数据
【发布时间】:2019-04-10 23:14:17
【问题描述】:

我对 VBA 还很陌生。我想创建一个用户表单,允许用户多次使用同一个表单。每次使用表单时,用户输入的任何数据都会添加到一个变量(相同的变量或多个不同的变量)中。当用户输入所有数据后,他们可以点击提交,表单将按顺序吐出所有数据。

示例: 带有文本框和 2 个命令按钮的用户表单,NextSubmit。 用户输入1,点击Next。用户输入2,点击Submit。 用户表单打印出1, 2

我该怎么做呢?这甚至可能吗?

【问题讨论】:

  • 完全有可能。存储提交的方式和位置由您决定(在集合、字典、数组、工作表中......)然后您只需检索并显示这些值。
  • 我对 VBA 非常陌生,并且一般都在编写代码(我没有这方面的背景)。解决此问题的最佳方法是什么?我希望用户能够决定他们输入数据的次数。所以有些用户可能只需要使用一次表单。其他人可能需要 5 个实例。我不需要您为我编写代码,但如果您能指出正确的方向,我将不胜感激!
  • 这类东西很难入门。我去过那儿。我已经在一个全新的工作簿上使用最简单的用户表单作为答案举了一个例子。这里我使用了一个名为Submissions 的数组来保存用户在TextBox1 中提交的值。要在创建用户表单并粘贴此代码后运行它,您可以转到 Immediate 窗格(查看>>立即)并输入 userForm1.Show 并按 Enter。

标签: excel vba


【解决方案1】:

这是一个快速 POC。考虑一个带有文本框和两个命令按钮的普通用户表单。我根本没有更改这里的默认名称。刚刚添加了一个带有 textbox1、commandbutton1 和 commandbutton2 的用户表单:

CommandButton1 提交,CommandButton2 退出用户表单(例如,当用户完成提交时单击)。

按照您的描述进行这项工作的代码。这在用户表单的代码页中。

'declare a string array to hold the submissions from textbox1
Private submissions() As String

'Code to run when the form activates
Private Sub UserForm_Activate()
    'When this userform is first initialized set up the array
    'as a one dimensional array with a single element
    ReDim submissions(0 To 0)
End Sub

'Code to run when the commandbutton1 is clicked
Private Sub CommandButton1_Click()
    'call the addSubmission sub
    addSubmission
End Sub

'Code to run when the commandButton2 is clicked
Private Sub CommandButton2_Click()

    'add submission one more time
    addSubmission

    'Now Loop through the array and send the values out
    'to the worksheet
    Dim rowCounter As Long
    rowCounter = 1
    For Each submission In submissions
        Sheet1.Cells(rowCounter, 1).Value = submission
        rowCounter = rowCounter + 1
    Next submission

    'Now close the form
    Me.Hide

    'And activate sheet1 for the user to see their submissions
    Sheet1.Activate
End Sub

'addSubmission will add textBox1 value to
'  the submissions array declared at the
'  top of this userform code.
Sub addSubmission()
    'First we have to redim the array to hold the new
    '   submission.
    'But only redim it if this isn't the first submission
    If UBound(submissions) > 0 Or submissions(0) <> "" Then ReDim Preserve submissions(0 To UBound(submissions) + 1)
    submissions(UBound(submissions)) = Me.TextBox1.Value

    'Clear the textbox so the user doesn't have to backspace
    Me.TextBox1.Value = ""
End Sub

【讨论】:

  • 非常感谢!这正是我所需要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-12
相关资源
最近更新 更多