为什么左函数返回一个运行时错误“424”?

问题描述 投票:2回答:2

下面的代码应该从细胞复制值和它的第10个字符粘贴到该范围内的相同的小区。在这条线:

Sh.Cells(i, 5) = Left(Sh.Cells(i, 5).Value, 10).Copy

我得到一个运行时错误“424”(所需的对象)。添加“设置”前行不起作用。有谁知道为什么在这里引发的错误?

Sub fixCellsValue()
    Dim wrk As Workbook
    Dim Sh As Worksheet
    Dim SourceFolder As String
    Dim i As Long, lastrow As Long

    SourceFolder = ThisWorkbook.PATH & "\source"

    If Dir(SourceFolder & "Filename.*") <> "" Then

        Set wrk = Application.Workbooks.Open(SourceFolder & "\Filename.xlsx")
        Set Sh = wrk.Worksheets(1)

        lastrow = Sh.Cells(Sh.Rows.Count, "A").End(xlUp).row

        For i = 2 To lastrow
            If Len(Sh.Cells(i, 5)) > 10 Then
                Sh.Cells(i, 5) = Left(Sh.Cells(i, 5).Value, 10).Copy
                Sh.Cells(i, 5).PasteSpecial Paste:=xlPasteValues
                Sh.Cells(i,5).Interior.ColorIndex = 6
            End If
        Next i
    End If
End sub
excel vba
2个回答
5
投票

你需要了解的方法和赋值操作是如何工作的。

Sh.Cells(i, 5) = Left(Sh.Cells(i, 5).Value, 10).Copy

这是分配左侧(LHS)表达Sh.Cells(i, 5).Value(通过一个隐含的默认成员调用)由右边(RHS)表达式返回的值 - 但在RHS不返回任何东西。

Left(Sh.Cells(i, 5).Value, 10)

此表达式返回Variant/String即最多10个字符长。在VBA,一个String仅仅是一个值(如一个或IntegerLong,除了它包含文本),并在VBA值不必构件的方法。

所以,你不能做到这一点:

Debug.Print "ABC".Copy

因为一个部件呼叫需要的对象 - 因此,所需的对象。

.Copy成员通话,你会修复此错误。


Sh.Cells(i, 5).PasteSpecial Paste:=xlPasteValues

这是技术上的冗余 - 它前行刚刚做正是这样,通过直接分配单元的Value。但是,如果你想调用Range.Copy,你不能这样做的RHS表达式的一部分,因为Range.Copy不返回任何东西 - 所以你会做这样的事情:

Sh.Cells(i, 5).Copy
Sh.Cells(i, 5).PasteSpecial Paste:=xlPasteValues

但话又说回来,这是多余的 - 你不必在这里涉及到剪贴板。


1
投票

我看到一些代码错误,请看:

  • If Dir(SourceFolder & "Filename.*") <> "" Then:没有一个结束如果在代码的末尾。
  • Sh.Cells(i, 5) = Left(Sh.Cells(i, 5).Value, 10).Copy:你不需要.copy末,你已经设置的值。

在最后你应该有这样的代码:

Sub fixCellsValue()
    Dim wrk As Workbook
    Dim Sh As Worksheet
    Dim SourceFolder As String
    Dim i As Long, lastrow As Long

    SourceFolder = ThisWorkbook.PATH & "\source"

    If Dir(SourceFolder & "Filename.*") <> "" Then

        Set wrk = Application.Workbooks.Open(SourceFolder & "\Filename.xlsx")
        Set Sh = wrk.Worksheets(1)

        lastrow = Sh.Cells(Sh.Rows.Count, "A").End(xlUp).row

        For i = 2 To lastrow
            If Len(Sh.Cells(i, 5)) > 10 Then
                Sh.Cells(i, 5) = Left(Sh.Cells(i, 5).Value, 10)
                Sh.Cells(i,5).Interior.ColorIndex = 6
            End If
        Next i
    End If
End sub
© www.soinside.com 2019 - 2024. All rights reserved.