从文本框中获取值并插入到Excel中

时间:2017-08-19 09:42:13

标签: excel vba excel-vba

我制作了一个表单来从textbox1textbox2textbox3获取值,然后点击添加按钮将这些值输入到电子表格中。见附图:

attached picture

但是我只能将数据插入到我的表单一次,并且所有3行都被相同的数据填充。

Private Sub Add_Click()

Dim roww As Integer
Dim colh As Integer

For colh = 0 To 2
    For roww = 0 To 2
        Range("A2").Offset(colh, roww).Value = Controls("TextBox" & roww + 1).Value
    Next roww
Next colh

End Sub

enter image description here

3 个答案:

答案 0 :(得分:2)

刚刚改进了Michal的答案,但我添加了最后一行的搜索条件和输入,这样您就可以添加所需的输入,而不会影响以前的输入。

 Private Sub Add_Click()

    Dim colh As Integer

    'This is to find the last row in your input sheet1 (?) whichever sheet you are doing input.
    Dim iRow as Long
    Dim ws as Worksheets("Sheet1") 'whatever name of sheet you have.
    iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
       SearchDirection:=xlPrevious, LookIn:=xlValues).row + 1

    For colh = 1 To 3
        ws.Cells(iRow , colh).Value = Controls("TextBox" & colh).Value
    Next colh

End Sub

答案 1 :(得分:1)

更改嵌套循环:

For colh = 0 To 2
    For roww = 0 To 2
        Range("A2").Offset(colh, roww).Value = Controls("TextBox" & roww + 1).Value
    Next roww
Next colh

简单循环:

For colh = 0 To 2
    Range("A2").Offset(colh, roww).Value = Controls("TextBox" & colh + 1).Value
Next colh

但是,在该循环之前,您必须指定roww(行偏移)。现在,单击按钮将只填充一行。

答案 2 :(得分:1)

方法1

在这里,我重构你可以正确定义你的值的目标范围,并纠正colh迭代列和控件。

Private Sub Add_Click()
    Dim colh As Long
    Dim Target As Range

    With Worksheets("Sheet1")
        Set Target = .Range("A" & .Rows.Count).End(xlUp).Offset(1)
    End With

    For colh = 1 To 3
        Target.Cells(1, colh) = Controls("TextBox" & colh).Value
    Next colh
End Sub

方法2

我就是这样做的。我定义了第二个子,它接受我写入目标范围的ParamArray值数组。通过这种方式,我可以为控件提供有意义的名称。

Private Sub btnAddMethod2_Click()
   AddRecord txtName.Value, txtAge.Value, txtPhoneNumber.Value
End Sub

Sub AddRecord(ParamArray Values())
    Dim Target As Range
    'Define Target Range
    With Worksheets("Sheet1")
        Set Target = .Range("A" & .Rows.Count).End(xlUp).Offset(1)
    End With

    Target.Resize(1, UBound(Values) + 1).Value = Values
End Sub

enter image description here