在vba中的特定行中添加数据

时间:2017-04-30 08:49:10

标签: excel vba excel-vba

点击命令按钮后,我希望我的excel能够:

  • 输入我在文本框中输入的内容/在特定列的组合框中选择而不删除我之前输入的内容

但此时,它无法正常工作或从文本框和组合框输入任何输入。

我写的脚本是:

Private Sub
    If TextBox1.Value = "" Or TextBox2.Value = "" Or TextBox3.Value = "" Then
        If MsgBox ("There might one or more empty cells, 
        do you want to continue to proceed?", vbQuestion + vbYesNo) <> vbYes Then
    Exit Sub
    End If
End If

Dim invsheet As Worksheet
Dim pacsheet As Worksheet

Set invsheet = ThisWorkbook.Sheets("INV")
Set pacsheet = ThisWorkbook.Sheets("PAC")

invsheet.Range("A1").Value = TextBox6.Text
invsheet.Range("I5").Value = TextBox7.Text
invsheet.Range("A21").Value = TextBox5.Text
invsheet.Range("A25").Value = ComboBox1.Value

inv_nr = invsheet.Cells(Row.Count, 1).End(xlUp).Row +1
invsheet.Cells(inv_nr, 5).Value = Me.TextBox1
invsheet.Cells(inv_nr, 4).Value = Me.ComboBox2

pac_nr = pacsheet.Cells(Row.Count, 1).End(xlUp).Row +1
pacsheet.Cells(pac_nr, 5).Value = Me.TextBox2
pacsheet.Cells(pac_nr, 5).Value = Me.TextBox3
pacsheet.Cells(pac_nr, 5).Value = Me.TextBox4

问题:

inv_nr = invsheet.Cells(Row.Count, 1).End(xlUp).Row +1
invsheet.Cells(inv_nr, 5).Value = Me.TextBox1
invsheet.Cells(inv_nr, 4).Value = Me.ComboBox2

pac_nr = pacsheet.Cells(Row.Count, 1).End(xlUp).Row +1
pacsheet.Cells(pac_nr, 5).Value = Me.TextBox2
pacsheet.Cells(pac_nr, 7).Value = Me.TextBox3      'mistyped it. supposed to be 7
pacsheet.Cells(pac_nr, 9).Value = Me.TextBox4      'mistyped it. supposed to be 9

此代码块不起作用,并在工作表上创建任何输出。

我将非常感谢你的帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

您没有在A列中放置任何内容(invsheet的A1,A21和A25除外),因此根据inv_nrpac_nr变量进行设置并不是一个好主意在A列的最后一个使用过的单元格中。

尝试将其基于您填充数据的其中一列,例如第5栏:

'Always qualify "Rows" (and don't mistype it as "Row")
inv_nr = invsheet.Cells(invsheet.Rows.Count, 5).End(xlUp).Row + 1
invsheet.Cells(inv_nr, 5).Value = Me.TextBox1
invsheet.Cells(inv_nr, 4).Value = Me.ComboBox2

'Always qualify "Rows" (and don't mistype it as "Row")
pac_nr = pacsheet.Cells(pacsheet.Rows.Count, 5).End(xlUp).Row + 1
pacsheet.Cells(pac_nr, 5).Value = Me.TextBox2 'Note: This is pointless because the next line overwrites it
pacsheet.Cells(pac_nr, 5).Value = Me.TextBox3 'Note: This is pointless because the next line overwrites it
pacsheet.Cells(pac_nr, 5).Value = Me.TextBox4