值在列中粘贴两次

时间:2016-12-08 09:31:42

标签: excel-vba date userform vba excel

我的问题是列“A”。在此列中,今天的日期应粘贴在第一个空白行中。但是我把它贴了两次。第一次显示UserForm1时,第二次单击CommandButton1时。其他一切正常(来自UserForm1的数据被粘贴到最后一行+ 1。问题仅与列“A”有关。 请找到以下代码:

Private Sub CommandButton1_Click()


Call UserForm_Initialize

Unload Me
End Sub


Private Sub UserForm_Initialize()

Dim LastRow As Long, ws As Worksheet

'UserForm1.Label9.Caption = ws.Range("A1").Value

Set ws = Sheets("Log")

With ComboBox1
    .AddItem "Quality"
    .AddItem "Time"
    .AddItem "Money"
End With


LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'ostatni wiersz


'entry date
    ws.Range("A1").Copy
       Sheets("Log").Range("A" & LastRow).PasteSpecial xlPasteValues

'pasting data from form
'ws.Range("A" & LastRow).Value = Label9.Caption
ws.Range("B" & LastRow).Value = TextBox8.Text
ws.Range("C" & LastRow).Value = TextBox1.Text
ws.Range("D" & LastRow).Value = TextBox2.Text
ws.Range("E" & LastRow).Value = TextBox3.Text
ws.Range("F" & LastRow).Value = TextBox4.Text
ws.Range("G" & LastRow).Value = TextBox5.Text
ws.Range("H" & LastRow).Value = ComboBox1.Text
ws.Range("I" & LastRow).Value = TextBox6.Text
ws.Range("J" & LastRow).Value = TextBox7.Text
End Sub

请帮忙。

1 个答案:

答案 0 :(得分:0)

每次打开用户表单时都会执行

UserForm_Initialize()。因此,每次显示此用户表单时,您都会从UserForm_Initialize()执行整个代码,然后单击CommandButton1。您只在A列中看到问题,因为每个TextBox都是空的,因此您的程序无需填充其余的单元格。这里的解决方案将分离初始化Userform的代码部分和将值复制到单元格的部分。你可以这样做:

Private Sub CommandButton1_Click()
    CopyToCells
    Unload Me
End Sub

Private Sub UserForm_Initialize()
    With ComboBox1
        .AddItem "Quality"
        .AddItem "Time"
        .AddItem "Money"
    End With
End Sub

Sub CopyToCells()
    Dim LastRow As Long, ws As Worksheet
    Set ws = Sheets("Log")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).row + 1 'ostatni wiersz

    'entry date
    ws.Range("A1").Copy
    Sheets("Log").Range("A" & LastRow).PasteSpecial xlPasteValues

    'pasting data from form
    ws.Range("B" & LastRow).Value = TextBox8.Text
    ws.Range("C" & LastRow).Value = TextBox1.Text
    ws.Range("D" & LastRow).Value = TextBox2.Text
    ws.Range("E" & LastRow).Value = TextBox3.Text
    ws.Range("F" & LastRow).Value = TextBox4.Text
    ws.Range("G" & LastRow).Value = TextBox5.Text
    ws.Range("H" & LastRow).Value = ComboBox1.Text
    ws.Range("I" & LastRow).Value = TextBox6.Text
    ws.Range("J" & LastRow).Value = TextBox7.Text
End Sub