[英]VBA copy contents of a row and multiply it based on a cell value
我有以下代碼
Sub copy()
Dim rngSource As Range
Dim copyCount As Long
With Sheets("Sheet1").Range("H2")
copyCount = .Value
Set rngSource = .EntireRow.Range("C1:F1")
End With
With Sheets("Sheet2").Range("A2")
.Resize(copyCount, rngSource.Columns.Count).Value = rngSource.Value
End With
End Sub
它的作用:它將第一行的內容從 C1 復制到 sheet2 上的 F1,並根據 H2 的值乘以行數。 因此,如果單元格 H2 的編號為 4,它會從 Sheet1 中獲取從 C1 到 F1 的所有單元格,並在 Sheet2 中生成 4 行。 現在我希望它對 Sheet1 的每一行做同樣的事情,因為它目前只對 1 行進行操作。
我認為 For Each 循環是必需的,但我已經嘗試了幾次,但它失敗了。
任何幫助都會受到好評。 謝謝!
請嘗試下一個代碼。 我希望我正確理解了您的需求。 如果不是,請更好地描述它...
Sub copySpecial()
Dim sh1 As Worksheet, sh2 As Worksheet, lastRow1 As Long, lastRow2 As Long, arrC As Variant
Dim copyCount As Long, i As Long
Set sh1 = Sheets("Sheet1"): Set sh2 = Sheets("Sheet2")
lastRow1 = sh1.Range("C" & Rows.count).End(xlUp).row
For i = 2 To lastRow1
copyCount = sh1.Range("H" & i).Value
arrC = sh1.Range("C" & i & ":F" & i)
lastRow2 = sh2.Range("A" & Rows.count).End(xlUp).row + 1
If lastRow2 < 14 Then lastRow2 = 14
If copyCount > 0 Then
sh2.Range("A" & lastRow2).Resize(copyCount, 4).Value = arrC
End If
Next i
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.