VBA出现问题,为每个条目添加新行

时间:2018-11-26 05:13:02

标签: excel vba

几年前,我曾经玩过VBA,直到现在才需要它。

基本上,我只是为我们的生产人员创建一个数据输入表单。

我想要实现的是,每当用户单击“确定”时,它将数据添加到上一行下面的新行中。

我已经添加了一行,但是每次单击“确定”按钮时,它只会覆盖该行。

这是我的代码

Option Explicit

Private Sub CancelButton_Click()

Unload Me

End Sub

Private Sub ClearButton_Click()

Call UserForm_Initialize

End Sub

Private Sub OKButton_Click()

Dim emptyRow As Long

'Make Shearline active
Shearline.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 3

'Transfer information
Cells(emptyRow, 1).Value = datebox.Value
Cells(emptyRow, 2).Value = operatorbox.Value
Cells(emptyRow, 3).Value = customerbox.Value
Cells(emptyRow, 4).Value = schedulebox.Value
Cells(emptyRow, 5).Value = barmarkbox.Value
Cells(emptyRow, 6).Value = bardialist.Value
Cells(emptyRow, 7).Value = offcutusedbox.Value
Cells(emptyRow, 8).Value = qty6mbox.Value
Cells(emptyRow, 9).Value = qty12mbox.Value
Cells(emptyRow, 11).Value = cutlegnthbox.Value
Cells(emptyRow, 13).Value = tagqtybox.Value
Cells(emptyRow, 15).Value = offcutleftbox.Value
Cells(emptyRow, 17).Value = offcutqtybox.Value
Cells(emptyRow, 19).Value = heatbox.Value

End Sub

Private Sub UserForm_Initialize()

bardialist.AddItem "N10"
bardialist.AddItem "N12"
bardialist.AddItem "N16"
bardialist.AddItem "N20"
bardialist.AddItem "N24"
bardialist.AddItem "N28"
bardialist.AddItem "N32"
bardialist.AddItem "N36+"

'Empty Date
datebox.Value = ""

'Empty Operator
operatorbox.Value = ""

'Empty customer
customerbox.Value = ""

'Empty schedulebox
schedulebox.Value = ""

'Empty Bar Mark
barmarkbox.Value = ""

'Empty Offcut
offcutusedbox.Value = ""

'Empty QTY 6m
qty6mbox.Value = ""

'Empty QTY 12m
qty12mbox.Value = ""

'Empty Cut Legnth
cutlegnthbox.Value = ""

'Empty Tag
tagqtybox.Value = ""

'Empty Offcut left
offcutleftbox.Value = ""

'Empty Offcut QTY
offcutqtybox.Value = ""

'Empty Heat
heatbox.Value = ""

'Set Focus on customer
datebox.SetFocus

End Sub

1 个答案:

答案 0 :(得分:-2)

关闭,您需要找到最后一行。

替换此

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 3

为此

'Determine emptyRow
emptyRow  = Sheets("sheet name here").Range("A" & Rows.Count).End(xlUp).Row + 1

在此处将工作表名称更改为您的实际工作表名称。确保保留"

使用+1的原因是最后一行代码获取该列中最后使用的单元格。当您需要下一个空白单元格时,我们+1

要添加,我们通常会调用LastRow或以上类似的公式。如果您进行搜索,这通常会显示出来

但是,做到这一点并为将来提供安全证据的更好方法是设置工作表和工作簿。

因此:

DIM wb As Workbook
DIM wks As Worksheet

Set wb As ThisWorkbook
Set wks As wb.Sheets("add sheet name")

'Determine emptyRow
emptyRow  = wks.Range("A" & Rows.Count).End(xlUp).Row + 1