复制范围键入不匹配错误。

时间:2014-01-13 05:58:21

标签: excel excel-vba vba

我正在努力使这项工作,但它说Type mismatch。对我做错的任何帮助? (我对此很新)

Sub Copy_paste_XP()

Dim wsI As Worksheet
Dim aCell As Range, rngCopyFrom As Range, rng As Range
Dim lRow As Long

Set wsI = ThisWorkbook.Sheets("Move containers XP")

Set rng = ("E2:E500")

For Each aCell In rng
    If Len(Trim(aCell.Value)) <> 0 Then
        If rngCopyFrom Is Nothing Then
            Set rngCopyFrom = aCell
        Else
            Set rngCopyFrom = Union(rngCopyFrom, aCell)
        End If
    End If
Next

If Not rngCopyFrom Is Nothing Then rngCopyFrom.Copy

Range("K2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Set rng = ("F2:F500")

For Each aCell In rng
    If Len(Trim(aCell.Value)) <> 0 Then
        If rngCopyFrom Is Nothing Then
            Set rngCopyFrom = aCell
        Else
            Set rngCopyFrom = Union(rngCopyFrom, aCell)
        End If
    End If
Next

If Not rngCopyFrom Is Nothing Then rngCopyFrom.Copy
Range("K501").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

End Sub

2 个答案:

答案 0 :(得分:1)

首先,您没有正确设置变量。您使用Set rng = ("E2:E500")时应使用Set rng = wsI.Range("E2:E500")

此外,宏可以更灵活。以下代码应该有效:

Sub CopyNotZero(SrcRng As Range, DestRng As Range)
    Dim Cell As Range, RngToCopy As Range
    For Each Cell In SrcRng
        If Cell.Value <> 0 And Len(Cell.Value) <> 0 Then
            If RngToCopy Is Nothing Then
                Set RngToCopy = Cell
            Else
                Set RngToCopy = Union(RngToCopy, Cell)
            End If
        End If
    Next Cell
    If Not RngToCopy Is Nothing Then
        RngToCopy.Copy
        DestRng.PasteSpecial xlPasteValues
    End If
    Set RngToCopy = Nothing
End Sub

像这样使用:

Sub Test()
    Dim wsI As Worksheet: Set wsI = ThisWorkbook.Sheets("Move containers XP")
    With wsI
        CopyNotZero .Range("E1:E500"), .Range("K2")
        CopyNotZero .Range("F1:F500"), .Range("K501")
    End With
End Sub

这将跳过具有0值或根本没有值的所有单元格。

<强> 截图:

设置向上:

enter image description here

运行Test()后的结果:

enter image description here

希望这有帮助。

修改

要在每次粘贴到$A$2时调用此宏,以下代码将起作用(相应地进行修改):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$A$2" Then
        CopyNotZero Range("A1:A500"), Range("K2")
    End If
End Sub

希望这有帮助。

答案 1 :(得分:0)

  

E2:E500&lt; ----这是我选择的。我试图让它复制e2:e500并在K2中按值粘贴然后复制f2:f500然后将它们按K501中的值粘贴,同时排除0或空白 - 禁止9分钟前

     

设置rng =(“E2:E500”)

您遗漏了Range这个词。将其更改为

Set rng = wsI.Range("E2:E500")

修改

同样适用于Set rng = ("F2:F500")

此外,这似乎是您PREV问题的后续内容。我发现你还在使用.Select;)