使用Excel Userform剪切具有“x”的行,删除行,并粘贴到不同的工作表中

时间:2016-10-31 21:01:22

标签: excel vba paste userform

在Excel中创建一个用户窗体,该用户窗体将在用户窗体上输入的列“B”中删除一行,然后将该行粘贴到sheet2中,同时还从用户窗体中添加3个值。这就是我所拥有的,但目前它对我没有任何作用:

Private Sub OkButton2_Click()

Dim i As Long: i = 1
With ActiveSheet
    For n = nLastRow To nFirstRow Step -1
        If .Cells(n, "B") = "ChartTextBox2.Value" Then
            .Cells(n, "B").EntireRow.Cut Sheet2.Cells(i, "A")
            .Cells(n, "B").EntireRow.Delete
            i = i + 1
'Transfer information
Sheets("Sheet2").Cells(emptyRow, 7).Value = DTPicker4.Value
Sheets("Sheet2").Cells(emptyRow, 8).Value = DispoTextBox.Value
Sheets("Sheet2").Cells(emptyRow, 9).Value = ReasonTextBox.Value
        End If
    Next
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

下面的代码对我来说很好。您要与文字"ChartTextBox2.Value"或文本框ChartTextBox2中的文字进行比较吗?假设您正在与文本框中的文本进行比较,下面的代码对我来说很好。您的代码nLastRownFirstRow也未声明。如果不是这种情况,您可以删除这些陈述。

Private Sub OkButton2_Click()
  Dim nLastRow As Long  'If already declared neglect this statement
  Dim nFirstRow As Long 'If already declared neglect this statement
  Dim i As Long: i = 1

  nLastRow = ActiveSheet.UsedRange.Rows.Count   'If already specified neglect this statement
  nFirstRow = ActiveSheet.UsedRange.Row         'If already specified neglect this statement

  With ActiveSheet
    For n = nLastRow To nFirstRow Step -1
      If .Cells(n, "B") = ChartTextBox2.Value Then
        .Cells(n, "B").EntireRow.Cut Sheets("Sheet2").Cells(i, "A")
        .Cells(n, "B").EntireRow.Delete
        i = i + 1
        'Transfer information
        Sheets("Sheet2").Cells(emptyRow, 7).Value = DTPicker4.Value
        Sheets("Sheet2").Cells(emptyRow, 8).Value = DispoTextBox.Value
        Sheets("Sheet2").Cells(emptyRow, 9).Value = ReasonTextBox.Value
      End If
    Next
  End With
End Sub