繁体   English   中英

如何将固定单元格复制到最外面的空单元格中

[英]How do I copy a fixed cell into the outermost empty cell

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

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

下面将计算使用的最后一列(在第 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM