我正在使用以下代碼嘗試將列表動態地複製到另一個工作表。它運行,但不是複製,而是刪除源工作表上的所有列E,並且不會將任何內容移動到目標工作表。我不確定發生了什麼,有什麼建議嗎?如何使用for循環VBA有條件地複製和粘貼行Excel
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
爲什麼在循環中創建變量?將您的Dim從您的循環移至工作簿的開頭。它也看起來像你正在分配循環中的單元格(i,5)到「」(因爲CellVal是空的)。它看起來像你想要的是cellVal = Cells(i,5).Value。我還建議調試你的crange以確保它正確設置。我沒有見過以前那樣使用過。我只看到它在Class模塊中使用。 –