Excel 向特定范围的列添加数据
我有一个userform,每次我用新数据填写文本框时,我都想添加一些单元格数据。我试了一下,但第一排不行Excel 向特定范围的列添加数据,excel,vba,Excel,Vba,我有一个userform,每次我用新数据填写文本框时,我都想添加一些单元格数据。我试了一下,但第一排不行 Dim i As Integer For i = 19 To 33 Cells(i, 4) = TextBox1.Value Cells(i, 5) = TextBox2.Value Cells(i, 6) = TextBox3.Value Cells(i, 7) = TextBox4.Value Cells(i, 8) = TextBox5.Value TextBox1.Value
Dim i As Integer
For i = 19 To 33
Cells(i, 4) = TextBox1.Value
Cells(i, 5) = TextBox2.Value
Cells(i, 6) = TextBox3.Value
Cells(i, 7) = TextBox4.Value
Cells(i, 8) = TextBox5.Value
TextBox1.Value = ""
TextBox2.Value = ""
TextBox3.Value = ""
TextBox4.Value = ""
TextBox5.Value = ""
Next i
End Sub
这是im制作表单的一部分:
如果使用Variatus提供的编码,它会将数据插入不在所需范围内的单元格中。我以前试过,但我也遇到过。这就是为什么我要尝试一个for和一个loop,或者一个do/while来观察这些单元格范围内的路径
(我展示的示例是在D列/第19行插入第一个TextBox1值)我不是100%了解您想要实现的目标,但是如果您希望简单地添加“D”列中的下一行数据,您可以使用以下命令 我包含的函数
LastRow
I将确定指定列中指定工作表中包含数据的最后一行-在调用子例程中向该图添加1只会将数据连续添加到下一可用行。希望这有帮助
Private Sub CommandButton1_Click()
Dim i As Integer
i = LastRow("Sheet1", "D") + 1
Cells(i, 4) = TextBox1.Value
Cells(i, 5) = TextBox2.Value
Cells(i, 6) = TextBox3.Value
Cells(i, 7) = TextBox4.Value
Cells(i, 8) = TextBox5.Value
TextBox1.Value = ""
TextBox2.Value = ""
TextBox3.Value = ""
TextBox4.Value = ""
TextBox5.Value = ""
End Sub
Function LastRow(wsheet As String, col As String) As Long
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets(wsheet)
LastRow = ws.Cells(Rows.Count, col).End(xlUp).Row
End Function
下面的代码将执行您想要的操作。每次它都会将5个文本框的内容写入工作表中的新行,然后删除文本框中的内容。如果要控制重复此操作的次数,则需要为此创建另一个过程
Sub CommandButton1_Click()
Dim Rt As Long ' row to write to
With Worksheets("Sheet1") ' change point at the correct tab
' find the last used row in columns(4) and add 1
Rt = .Cells(.Rows.Count, 4).End(xlUp).Row + 1
Cells(Rt, 4) = TextBox1.Value
Cells(Rt, 5) = TextBox2.Value
Cells(Rt, 6) = TextBox3.Value
Cells(Rt, 7) = TextBox4.Value
Cells(Rt, 8) = TextBox5.Value
End With
TextBox1.Value = ""
TextBox2.Value = ""
TextBox3.Value = ""
TextBox4.Value = ""
TextBox5.Value = ""
End Sub
使用下面给出的语法可以更有效地编写相同的代码。功能上没有区别。E&EO,因为我没有测试。)
您能解释一下“但它不会通过第一行”的意思吗?您的代码将用文本框中的数据填充范围(D19:H19)。然后,它将删除这些相同文本框的内容,并继续用文本框中的空字符串填充D20:H33范围。我想说代码按设计工作,但设计可能不是你想要的。@Variatus我需要的是:用户将填充文本框。然后按下按钮后,将数据添加到该范围的第一行。然后让用户添加新数据并重复该过程。无法让用户输入新数据而无需重复。@bigben第一行是数据插入到我需要的范围内的第一行。这很好。我有一些合并的单元格,所以我不得不稍微改变一下,但效果不错!我测试了第一个代码,但是
rows.count,4
的问题是数据将插入到我需要的范围之外的单元格中。我测试了多个值,但它不会在我需要的列中插入这些值,至少是我尝试过的。我添加了一个我在excel上制作的表单截图,所以你可以看到我的意思。这是合并单元格的诅咒。如果你在问题中提到他们,我会给出不同的答案。我指出,您的“自己的”解决方案还将获得第4列(D列)中最后使用的行。删除了有问题的合并单元格后,您现在应该可以自由部署我的答案了。它有更好的语法。
Sub CommandButton1_Click()
Dim Target As Range ' first cell to write to
Dim i As Long ' loop counter: offset
With Worksheets("Sheet1") ' change point at the correct tab
' find the last used row in columns(4) and add 1
Set Target = .Cells(.Rows.Count, 4).End(xlUp)
End With
For i = 1 To 5
With Me.Controls("TextBox" & i)
Target.Offset(, i + 3).Value = .Value
.Value = ""
End With
Next i
End Sub