我试图创建一个Excel VBA函数,它将复制工作表1中单元格中的数据并将其粘贴到工作表2中。理想情况下,我正在检查单元格AF6, AF7...
一直到“行“是。如果单元格内的值等于1,则代码将复制行“C”中的所有列出的列(在第一个实例中为第6行)并将它们粘贴到第2行(6-4)中。一些单元格包含数字,另一些包含字符串我被困 - 如果有人能解决我的问题,我真的很感激。
Public Sub copy_cells(rows As Integer)
Dim C As Integer
For C = 6 To C = rows
If Worksheets("sheet1").Range("AF" & C).Value = 1 Then
Sheet2.Range("B" & C).Value = Sheet1.Range("B" & C - 4).Value
Sheet2.Range("E" & C).Value = Sheet1.Range("C" & C - 4).Value
Sheet2.Range("I" & C).Value = Sheet1.Range("D" & C - 4).Value
Sheet2.Range("J" & C).Value = Sheet1.Range("E" & C - 4).Value
Sheet2.Range("R" & C).Value = Sheet1.Range("F" & C - 4).Value
Sheet2.Range("V" & C).Value = Sheet1.Range("G" & C - 4).Value
Sheet2.Range("C" & C).Value = Sheet1.Range("H" & C - 4).Value
Sheet2.Range("F" & C).Value = Sheet1.Range("J" & C - 4).Value
Sheet2.Range("G" & C).Value = Sheet1.Range("K" & C - 4).Value
Sheet2.Range("D" & C).Value = Sheet1.Range("N" & C - 4).Value
End If
C = C + 1
Next C
End Sub
答案 0 :(得分:2)
将您的For行更改为:
For C = 6 To rows
C = rows
评估为false (0)
,您永远无法访问for循环内的代码(For 6 to 0
)
答案 1 :(得分:1)
您的代码非常接近正常运行。两个变化:校正FOR
循环的迭代部分;并删除循环底部不必要的C显式迭代。
Option Explicit
Public Sub copy_cells(rows As Integer)
Dim C As Integer
For C = 6 To rows
If Worksheets("Sheet1").Range("AF" & C).Value = 1 Then
Sheet2.Range("B" & C).Value = Sheet1.Range("B" & (C - 4)).Value
Sheet2.Range("E" & C).Value = Sheet1.Range("C" & (C - 4)).Value
Sheet2.Range("I" & C).Value = Sheet1.Range("D" & (C - 4)).Value
Sheet2.Range("J" & C).Value = Sheet1.Range("E" & (C - 4)).Value
Sheet2.Range("R" & C).Value = Sheet1.Range("F" & (C - 4)).Value
Sheet2.Range("V" & C).Value = Sheet1.Range("G" & (C - 4)).Value
Sheet2.Range("C" & C).Value = Sheet1.Range("H" & (C - 4)).Value
Sheet2.Range("F" & C).Value = Sheet1.Range("J" & (C - 4)).Value
Sheet2.Range("G" & C).Value = Sheet1.Range("K" & C - 4).Value
Sheet2.Range("D" & C).Value = Sheet1.Range("N" & C - 4).Value
End If
Next C
End Sub