VBA- 将值从一个单元格复制到另一个偏移单元格

VBA- Copying Values from one cell to another offset cell

我正在尝试浏览第 6 行和第 1 列到第 26 列,并搜索句子 Earned Cumulative Hours。完成后,我将尝试从第 8 行转到最后一行(在本例中为 30),以获得在第 6 行中获得累积小时数的列。 然后我试图将此列中单元格的值粘贴到同一行中剩下的 2 个单元格。但我不断收到错误,代码无法运行。

有人能给我指出正确的方向吗?谢谢

 Sub project()

    Dim lastrow As Long
    Dim i As Long
    Dim j As Long

    lastrow = Sheets("Progress").Cells(Rows.Count, 26).End(xlUp).Row

    For j = 1 To 26
        If Cells(6, j) = "Earned Cumulative Hours" Then
            For i = 8 To lastrow
                Cells(i, j).Copy
                Cells(i, j).Offset(0, -2).Select
                Selection.PasteSpeical Paste:=xlPasteValues
            Next i
        End If
    Next j
End Sub

试试这个,我们可以摆脱那些选择

Sub project()

Dim lastrow As Long
Dim i As Long
Dim j As Long

lastrow = Sheets("Progress").Cells(Rows.Count, 26).End(xlUp).Row

For j = 1 To 26

    If Cells(6, j) = "Earned Cumulative Hours" Then

        For i = 8 To lastrow

            Cells(i, j).Copy
            With Cells(i, j)
                .Offset(0, -2).PasteSpecial xlPasteValues
            End With
        Next i ' next row
    End If
Next j ' next col
End Sub

我可以直接从您的代码中看出一些问题。首先,如果您要向后偏移两列 .Cells(i, j).Offset(0, -2),那么您将覆盖现有值。如果这是你打算做的,那就奇怪了,但没问题。

下一个问题是,如果 'Earned Cumulative Hours' 在 A 列中,您会遇到问题。如果是这种情况,Excel 将最不高兴尝试向左偏移两列,并且会给出一个错误。

在这种情况下,将一列中的值设置为另一列中的值而不是复制和粘贴会更有效,您可以在我的代码中看到这一点。最后,您的单元格引用仅对活动 sheet 有效。您需要限定您感兴趣的工作sheet,如我的代码所示。如果它是一个独立的块,我通常将它放在代码的开头。

您也可以消除 i 循环并一次设置值的范围,但我们会在下次保存它!

我还没有测试这段代码,但应该没问题。

Sub projectawesome()

    Dim lastrow as Long, i as Long, j as Long

    'Qualify the sheet (assuming its in the activeworkbook)
    With Sheets("Progress")
        lastrow = .Cells(.Rows.Count, 26).End(xlUp).Row

        'I've changed this to column three to prevent offset errors.
        For j = 3 to 26
            If .Cells(6, j) = "Earned Cumulative Hours" Then
                For i = 8 to lastrow
                   'Assuming overwriting data is ok.
                   'No need to copy and paste
                   .Cells(i, j - 2).Value = .Cells(i, j).Value
                Next i
            End If
        Next 
    End With
End Sub