将Excel VBA的数值复制粘贴到第一个空行。

3
我正在尝试设置一个Excel宏VBA,它能够执行以下操作:
将B16的值复制,并将其作为值粘贴到B26下的第一行空白行(因此,如果B26、B27不为空,会将该值粘贴到B28)。
同时,也将A16的值复制并在同一行中粘贴到A列,C16的值与其他值一起复制并粘贴到C列。
所以如果B26、B27和B28都已满,则VBA会从A16、B16和C16中复制值,并将它们粘贴到相应列的第一个可用行中(在此示例中,它将是A29、B29和C29)。

1
你尝试过使用什么代码来解决这个问题吗? - Skin
1个回答

1

复制值到第一个空单元格的行

  • 从单元格B26(含)向下查找,尝试找到一个空单元格。如果找到,它将把范围A16:C16的值复制到相同列的找到的单元格所在的行。
Option Explicit

Sub CopyToFirstEmptyCell()
    
    Const sAddress As String = "A16:C16"
    Const dAddress As String = "B26"
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    ' Reference the source range.
    Dim srg As Range: Set srg = ws.Range(sAddress)
    
    ' Reference the first empty cell below the given cell (inclusive).
    Dim dfCell As Range
    With ws.Range(dAddress) ' from the first cell...  ("B26:B1048576")
        With .Resize(ws.Rows.Count - .Row + 1) ' ...  to the bottom-most cell
            Set dfCell = .Find("", .Cells(.Cells.Count), xlFormulas, xlWhole)
            If dfCell Is Nothing Then ' no cells are empty; highly unlikely
                MsgBox "No empty cells.", vbCritical
                Exit Sub
            End If
        End With
    End With
    
    ' Reference the destination range.
    Dim drg As Range: Set drg = srg.EntireColumn.Rows(dfCell.Row)
    ' srg                                "A16:C16"
    ' srg.EntireColumn                   "A:C"
    ' srg.EntireColumn.Rows(dfCell.Row)  "AdfCell.Row:CdfCell.Row"
    
    ' Copy values by assignment.
    drg.Value = srg.Value

End Sub

非常感谢!!!我尝试了您发送的第一个公式,它完美地运行,因为价值不总是在同一行,所以我可以编辑该公式(请参见以下)。我的问题现在是,如果我想将这些值复制到另一个工作表中,该公式会如何更改?非常感谢! - M9933
这是您首先发送的公式,我正在使用并希望将其复制到不同的工作表中的数值。 - M9933

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接