[英]How to copy and paste rows conditionally with for loop VBA Excel
我正在使用以下代碼嘗試將列表動態復制到另一個工作表。 它會運行,但不會復制,而只是刪除源工作表上的所有E列,並且不會將任何內容移至目標工作表。 我不確定發生了什么,有什么建議嗎?
Option Explicit
Sub findCells()
Dim topCell As String
Dim leftCell As String
Dim refCell As Range
Dim sht As Worksheet
Dim lastRow As Long
Dim i As Long
Set refCell = ActiveCell
topCell = refCell.End(xlUp).Value
leftCell = refCell.End(xlToLeft).Value
MsgBox topCell
MsgBox leftCell
Worksheets(topCell).Activate
Set sht = Worksheets(topCell)
lastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
MsgBox lastRow
For i = 1 To lastRow
Dim cellVal As String
Dim altCounter As Integer
altCounter = 31
Cells(i, 5).Value = cellVal
If leftCell = cellVal Then
Dim crange As Range
altCounter = altCounter + 1
Let crange = "A" & i & ":" & "G" & i
Range(crange).Copy Worksheets("Summary").Range("A" & altCounter & ":" & "G" & altCounter)
End If
Next i
End Sub
這不是完整的答案,但是您在For i = 1 To lastRow
循環中有一些錯誤(寫為注釋太長了)。
首先,使用定義和設置的sht
對象完全限定Cells
和Range
。
其次,無需在每次進入循環時都聲明變量( cellVal
, altCounter
和crange
)。
第三,要設置一個范圍,則Let crange = "A" & i & ":" & "G" & i
會產生錯誤,您需要使用Set crange = .Range("A" & i & ":" & "G" & i)
。
第四,沒有在代碼中向cellVal
,所以我認為您在Cells(i, 5).Value = cellVal
應為cellVal = .Cells(i, 5).Value
Dim cellVal As String
Dim altCounter As Long '<-- use Long instead of Integer
Dim crange As Range
With sht
altCounter = 31
For i = 1 To lastRow
cellVal = .Cells(i, 5).Value
If leftCell = cellVal Then
altCounter = altCounter + 1
Set crange = .Range("A" & i & ":" & "G" & i)
crange.Copy Worksheets("Summary").Range("A" & altCounter & ":" & "G" & altCounter)
End If
Next i
End With
這也太長了,無法發表評論,但是感謝Shai Rado-這是一個完整的答案,並且代碼在我實現后就可以使用了。
但是,當我編輯以下內容后,它停止工作。 它不會引發錯誤,只是不會像以前一樣復制和粘貼行。
我不確定發生了什么,但是當我使用MsgBox驗證代碼的某些部分時,似乎是循環無法正常工作。 但是,沒有引發錯誤,我不知道為什么。
Option Explicit
Sub findCells()
Dim topCell As String
Dim leftCell As String
Dim refCell As Range
Dim sht As Worksheet
Dim lastRow As Long
Dim i As Long
Dim cellVal As String
Dim altCounter As Long
Dim crange As Range
Dim rangeToDelete As Range
Set rangeToDelete = Worksheets("Summary").Cells(31, "A").CurrentRegion
rangeToDelete.Value = ""
Set refCell = ActiveCell
topCell = refCell.End(xlUp).Value
leftCell = refCell.End(xlToLeft).Value
Set sht = Worksheets(topCell)
lastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
With sht
.Range("A1:G1").Copy Worksheets("Summary").Range("A31:G31")
altCounter = 31
For i = 1 To lastRow
cellVal = Cells(i, 5).Value
If leftCell = cellVal Then
altCounter = altCounter + 1
Set crange = .Range("A" & i & ":" & "G" & i)
crange.Copy Worksheets("Summary").Range("A" & altCounter & ":" & "G" & altCounter)
End If
Next i
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.