Excel VBA:用户表单代码将替换行内容,而不是添加新内容



我是一个初学者,正在学习用VBA编写代码,这是我的第一篇文章。我最近一直在为如何让我的UserForm工作而苦恼。

这是我的UserForm中"添加"按钮的代码,当我运行该宏时(通过按下添加按钮(,它会占据我工作表的顶行并替换单元格的内容。

我试图实现的实际上是在表单中添加一个新行,其中包含我输入的所有信息。这几天我一直在挣扎,所以这就是为什么(在谷歌上密集搜索后(我最终决定向你们寻求帮助:(希望我足够清楚。

祝你今天愉快,

Dim L As Integer

If MsgBox("Are you sure to create a new row with those information ?", vbYesNo, "Confirmation") = vbYes Then L = Sheets("BDD").Range("A65536").End(xlUp).Row + 1 'Adding the new line to the sheet

Range("B" & L).Value = CboResp.Text
Range("C" & L).Value = CboStat.Text
Range("D" & L).Value = CboNat.Text
Range("E" & L).Value = CboPrio.Text
Range("F" & L).Value = CboAff.Text
Range("G" & L).Value = CboLea.Text
Range("H" & L).Value = txtDateRD.Text
Range("I" & L).Value = txtDateEnv.Text
Range("J" & L).Value = CboIni.Text
Range("K" & L).Value = CboISAV.Text
Range("L" & L).Value = txtVin.Text
Range("M" & L).Value = txtContrat.Text
Range("N" & L).Value = txtClientFinal.Text
Range("O" & L).Value = txtImmat.Text
Range("P" & L).Value = txtNomCon.Text
Range("Q" & L).Value = txtPrenomCon.Text
Range("R" & L).Value = txtTelCon.Text
Range("S" & L).Value = txtMotif.Text
Range("T" & L).Value = txtDateRDV.Text
Range("U" & L).Value = txtDateInter.Text
Range("V" & L).Value = CboVH.Text
Range("W" & L).Value = txtComment.Text
Range("X" & L).Value = CboCon.Text

End If

这会更健壮:

Dim L As Long
If MsgBox("Are you sure to create a new row with those information ?", vbYesNo, "Confirmation") = vbYes Then
With Sheets("BDD")
L = .Range("A65536").End(xlUp).Row + 1 'Adding the new line to the sheet
.Range("B" & L).Value = CboResp.Text
.Range("C" & L).Value = CboStat.Text
.Range("D" & L).Value = CboNat.Text
.Range("E" & L).Value = CboPrio.Text
.Range("F" & L).Value = CboAff.Text
.Range("G" & L).Value = CboLea.Text
'etc etc
End with
End If

假设每一行添加的数据在ColA中总是有一个值。

最新更新