首页 > 解决方案 > 如何将固定单元格复制到最外面的空单元格中

问题描述

我正在尝试将固定列范围 (D20:D39) 复制到一个空列中,例如 K20:K39。每次我更新 (D20:D39) 时,列都会不断更新,即当我想复制 (D20:D39) 时,K、L、M、N... 将得到更新。我不精通编码或计算机科学,只是想让我的电子表格高效。有谁能帮忙吗?

我查看了其他一些线程,但大多提到复制到单独的工作表中。没有人提到这种“滚动”复制粘贴机制。

标签: excel

解决方案


下面将计算使用的最后一列(在第 20 行,因为我们将复制到那里)然后将列值设置为与范围 D20 到 D39 相同的列值:

Sub coppercopy()
Dim lastcol As Integer

lastcol = Sheets("Sheet1").Cells(20, Columns.Count).End(xlToLeft).Column
Range(Cells(20, lastcol + 1), Cells(39, lastcol + 1)).Value = Range("D20:D39").Value

Range(Cells(42, lastcol + 1), Cells(32, lastcol + 1)).Value = Range("D42:D62").Value
End Sub

如果要复制和粘贴而不是将值设置为与范围相同,请使用以下命令:

Sub coppercopy()
Dim lastcol As Integer
lastcol = Sheets("Sheet1").Cells(20, Columns.Count).End(xlToLeft).Column
Range("D20:D39").copy
Cells(20, lastcol + 1).PasteSpecial xlPasteValues
End Sub

编辑,第一个选项被编辑以包含更多范围。这可以在同一行上完成,但为了代码的可读性和易用性,我将它放在了一个新行上。请注意,与Cells(语句不同,语句始终采用 R1C1 表示法Range(。意思是它引用Cells(Row number, Column number). 牢记这一点,可以通过更新到正确的单元格引用轻松更新以包含要复制的任何范围。

第二次编辑: 根据评论,范围需要更加动态,同时sum在复制时仍要摆脱公式。以下子程序适用于此。它将从 D20 开始复制整个范围到最后填充的行,并根据需要将其复制到下一个可用列中。然后它在整个复制范围+1上循环(这是为了说明sum需要删除的范围末尾的公式),如果找到空白(表示新的“段落”),它会删除上面的单元格(总是sum最后一段的公式)。

Sub coppercopy()
Dim lastcol As Integer, lastr As Integer, cel As Range

lastcol = Sheets("Sheet1").Cells(20, Columns.Count).End(xlToLeft).Column 'determine last column with values
lastr = Sheets("Sheet1").Range("D" & Rows.Count).End(xlUp).Row 'determine last row with values

Range(Cells(20, lastcol + 1), Cells(lastr, lastcol + 1)).Value = Range("D20:D" & lastr).Value 'copy range to column after last used one

For Each cel In Range(Cells(20, lastcol + 1), Cells(lastr + 1, lastcol + 1)) 'If the copied range does not end with a sum formula, omit the `+ 1` after `lastr`.
    If cel.Value = "" Then 'loops over all cells and checks for blanks
        cel.Offset(-1, 0).Value = "" 'if blank is found, delete cell above
    End If
Next cel
End Sub

推荐阅读