首页 > 解决方案 > 有没有办法根据从文本框输入的数字在用户窗体中循环命令按钮?

问题描述

和我的其他帖子一样,请原谅我在这个主题上缺乏知识,我对编码很陌生。

我有一个用户表单,它有多个文本框,用户可以在其中输入数据。一旦该数据输入到表单中,用户单击命令按钮,代码将数据输出到它找到的第一个空行。这部分代码运行良好。

我的问题:如何循环命令按钮以单击自身“n”次,其中 n = data_points_textbox.Value。我的目标是能够让宏通过单击生成大量数据。

我已经尝试过像这样的帖子一个 VBA 循环通过用户窗体上的按钮

https://social.msdn.microsoft.com/Forums/en-US/bcb8b8b4-4bcf-404d-9fdb-a9d5f31f6b19/loop-through-excel-userform-textcombo-box-and-write-to-worksheet?forum=伊维巴

虽然有帮助,但我不确定这些帖子是否完全适用于我的情况,我也不确定我是否真的理解他们在做什么。

'Here is an excerpt of the code I am using, for various reasons I can't post all of it

Private Sub Data_Generator_Initialize()

'Empty Type_textbox
type_textbox.value = ""

End Sub 

Private Sub Generate_data_button_Click()

'Make sheet1 active
Sheet1.activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Transfer data to sheet1
Cells(emptyRow, 1).Value = type_textbox.Value 

End Sub 

'I have about 20 additional cells that are populated with data from various textboxes but I think this illustrates the point

标签: excelvbauserform

解决方案


我理解问题的方式:

  1. UF 上的按钮当前将文本框中的值输出到单行
  2. 根据另一个文本框的值,您希望输出到 x 行

这可以通过循环链接到命令按钮的宏内的代码来实现

Private Sub Generate_data_button_Click()
Dim arr(5) As String
Dim i As Long
Dim LRow As Long
Dim FEmptyRow As Long

'Using 6 textboxes as an example. Change to your configuration 
arr(0) = TextBox1.Value
arr(1) = TextBox2.Value
arr(2) = TextBox3.Value
arr(3) = TextBox4.Value
arr(4) = TextBox5.Value
arr(5) = TextBox6.Value

With Workbooks(REF).Sheets(REF)
    For i = 1 To data_points_textbox.Value
        LRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1 'determines the last filled row in column A
        FEmptyRow = .Cells(1, "A").End(xlDown).Row + 1 'determines the first empty row as seen from the top row (using this can cause filled rows below it to be overwritten!)

        .Range("A" & LRow & ":F" & LRow).Value = arr
        '.Range("A" & FEmptyRow & ":F" & FEmptyRow).Value = arr  'Alternative with the first empty row
    Next i
End With
End Sub

推荐阅读