【问题标题】:Excel VBA: Userform code replaces row content instead of adding a new oneExcel VBA:用户表单代码替换行内容而不是添加新内容
【发布时间】:2020-08-11 05:31:07
【问题描述】:

我是一名初学者,正在学习使用 VBA 编写代码,这是我的第一篇文章。我最近一直在努力让我的 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

【问题讨论】:

  • 如果最后一行数据中的 Col A 没有值,就会发生这种情况。

标签: excel vba userform


【解决方案1】:

这样会更健壮:

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 中始终存在一个值。

【讨论】:

  • 您对范围的看法是正确的。由于 A 列是空白的,因此代码不起作用。按照您的建议,将范围更改为 B,现在一切正常!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-11
相关资源
最近更新 更多