VBA正确输入下一个空行的用户表单数据

Pet*_*ete 3 excel vba excel-vba

  1. 创建了一个用户表单
  2. 添加了一个textBox和一个comboBox
  3. 添加了提交按钮
  4. 单击提交后,它会将数据添加到电子表格中

从我被告知的内容和我所读到的内容来看,这是错误的

ActiveCell.Value = TextBox3.Text 
ActiveCell.Offset(0, 1).Select   
ActiveCell.Value = ComboBox1.Text  
ActiveCell.Offset(1, -1).Select  
Run Code Online (Sandbox Code Playgroud)

这有效,但我被告知我不应该尽可能使用.select关键字.我已经读过,为了使我的代码可以重用,我应该创建变量.专业开发人员如何编写此代码,可以用更少的行编写,如何在不使用select的情况下引用activecell偏移?

Chr*_*007 12

我假设您想要TextBox3在A列和ComboBox1B列中.如果您想要不同的列,只需更改字母引用.

Sub OnClick() 'whatever your current sub is called.

    Dim LastRow As Long, ws As Worksheet

    Set ws = Sheets("Name of Sheet where data is going")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Finds the last blank row

    ws.Range("A" & LastRow).Value = TextBox3.Text 'Adds the TextBox3 into Col A & Last Blank Row
    ws.Range("B" & LastRow).Value = ComboBox1.Text 'Adds the ComboBox1 into Col B & Last Blank Row

End Sub
Run Code Online (Sandbox Code Playgroud)

如果你想要一个方法使用Offset():

Sub OnClickwithOffset() 'whatever your current sub is called.

    Dim LastRow As Long, ws As Worksheet

    Set ws = Sheets("Name of Sheet where data is going")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Finds the last blank row

    ws.Range("A" & LastRow).Value = TextBox3.Text 'Adds the TextBox3 into Col A & Last Blank Row
    ws.Range("A" & LastRow).Offset(0, 1).Value = ComboBox1.Text 'Adds the ComboBox1 into next cell to the right of TextBox3 data.

End Sub
Run Code Online (Sandbox Code Playgroud)