当我尝试一次提交多个条目时,VBA代码不起作用

时间:2015-12-01 17:09:33

标签: vba excel-vba excel

每当我将一个条目粘贴到第16列时,我都会使用这条VBA代码(请参阅下面的代码)。

然而,它给了我一个"运行时错误' 13':类型不匹配"每当我拖下价值" Keep - Not Action"或者如果我粘贴多个条目。

如果您对如何解决有任何疑问,请告诉我!

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim r As Integer
 If Target.Column = 17 Then
    If Target = "Keep - no action" Then
        r = Target.Row

        Cells(r, "T").Value = Cells(r, "N").Value
        Cells(r, "T").AutoFill Destination:=Range("T" & r & ":AC" & r), Type:=xlFillSeries 'Type:=xlFillDefault
    End If

    If Target = "req" Then
        MsgBox "Please enter new line item below"
    End If

 End If

End Sub

2 个答案:

答案 0 :(得分:0)

您没有在任何地方使用INTERSECT功能作为您的范围和目标,请调整以下代码供您使用:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng as range
set rng = ThisWorkbook.Worksheets("Sheet name").Range("P1",Range("P1048576").End(xlup))    
 Dim r As Integer
If Not Intersect(Target, rng) Is Nothing Then
    For Each Target In rng 
If Target.Column = 17 Then
        If Target = "Keep - no action" Then
            r = Target.Row

            Cells(r, "T").Value = Cells(r, "N").Value
            Cells(r, "T").AutoFill Destination:=Range("T" & r & ":AC" & r), Type:=xlFillSeries 'Type:=xlFillDefault
        End If

        If Target = "req" Then
            MsgBox "Please enter new line item below"
        End If

     End If
Next Target
end if   
End Sub

答案 1 :(得分:0)

您无需自动填充。

    Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Column <> 17 Then Exit Sub
    r = Target.Row
    If Target = "Keep - no action" Then
        Range("T" & r & ":AC" & r) = Cells(r, "N").Value
    End If

End Sub

可能循环通过每个单元格可以工作,

    Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rws As Long, rng As Range, c As Range
    On Error Resume Next
    rws = Cells(Rows.Count, 17).End(xlUp).Row
    Set rng = Range(Cells(1, 17), Cells(rws, 17))
    If Target.Column <> 17 Then Exit Sub

    For Each c In rng.Cells
        r = c.Row
        If c = "Keep - no action" Then
            Range("T" & r & ":AC" & r) = Cells(r, "N").Value
        End If
    Next c

End Sub