下面的代码应该从细胞复制值和它的第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
你需要了解的方法和赋值操作是如何工作的。
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
仅仅是一个值(如一个或Integer
被Long
,除了它包含文本),并在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
但话又说回来,这是多余的 - 你不必在这里涉及到剪贴板。
我看到一些代码错误,请看:
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