我有以下代码将从 Sheet1 复制和粘贴符合 E 列中关键字条件(里程碑)的行,并将行复制到 Sheet2。
然后在 Sheet2 上提取日期并输入到新列中,但我收到错误
下标超出范围(错误 9)
当这个动作完成时。
我看不出是什么原因造成的?
我还需要首先将第 10 行从 Sheet1 复制并粘贴到 Sheet2 中的第 1 行以用作数据透视表的类别?
Sub mileStoneDateChanger()
Dim r As Long, pasteRowIndex As Long, v() As Long, i As Long
Dim lastRow As Long
Dim lCol As Long
lastRow = Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
MsgBox "Last Row: " & lastRow
pasteRowIndex = 1
With Sheets("Sheet1")
For r = 1 To lastRow
If .Cells(r, "E").Value Like "Milestone*" Then
If UBound(Split(.Cells(r, "E"), ",")) > 0 Then
i = i + 1
ReDim v(1 To i)
v(i) = pasteRowIndex
End If
Sheets("Sheet1").Rows(r).Copy Sheets("Sheet2").Rows(pasteRowIndex)
pasteRowIndex = pasteRowIndex + 1
End If
Next r
End With
With Sheets("Sheet2")
newLastRow = Cells.Find(What:="*", _
After:=Range("B1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
If IsArray(v) Then
.Columns(6).Insert shift:=xlToRight
For i = 1 To newLastRow
.Cells(i, "F").Value = Split(.Cells(i, "E"), ",")(1)
Next i
End If
End With
End Sub
您收到超出范围的错误,因为您假设这里有一个逗号Cells(i,"E")
:
For i = 1 To newLastRow
.Cells(i, "F").Value = Split(.Cells(i, "E"), ",")(1)
Next i
使用上面的代码,您可以Cells(i,"E")
通过逗号获取来自 splitted 的数组的第二个值。这,如果单元格中的值为123,45
,您将采用45
。最有可能的情况是,您没有任何逗号,因此没有第二个值。因此,您必须进行检查。例如这样的事情:
If InStr(1, .Cells(i, "F"), ",") Then
.Cells(i, "F").Value = Split(.Cells(i, "E"), ",")(1)
End If
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句