【问题标题】:Paste selected range to another sheet将所选范围粘贴到另一个工作表
【发布时间】:2021-05-10 15:21:46
【问题描述】:

我有一个包含月度报告表的文件,还有一张包含所有这些月度报告的合并表。
我想构建一个 VBA 代码,让用户用鼠标选择一个范围(这目前有效),然后将所选范围粘贴到合并表中的最后一行 +1(我需要使用 B 列最后一行,然后移至 A 列,因为它在我的工作表中是必需的)。

到目前为止我构建的代码:

Sub miseAJour()

    Dim rng As Range
    Dim rgndest As Range
    Set rng = Application.InputBox("Select a range", "Obtain Range Object", Type:=8)
       
    Range("B" & Rows.Count).End(xlUp).Offset(1).Select
    ActiveCell.Offset(0, -1).Select
    
End Sub

缺少的部分是将 rng 粘贴到选定的活动单元格中。

【问题讨论】:

标签: excel vba


【解决方案1】:

Application.InputBox 带范围

  • 调整常量部分中的值。
Option Explicit

Sub miseAJour()
    
    ' Define constants.
    Const dName As String = "Consolidated"
    Const dlrCol As String = "B"
    Const dfCol As String = "A"
    
    ' Define Initial Range Address (the 'Default' parameter).
    Dim dAddress As String
    If TypeName(Selection) = "Range" Then
        dAddress = Selection.Address
    Else ' The current 'Selection' is not a range.
        dAddress = "$A$1"
    End If
    
    ' Attempt to create a reference to the Source (selected) Range.
    Dim srg As Variant
    On Error Resume Next
    Set srg = Application.InputBox( _
        Prompt:="Select a range", Title:="Obtain Range Object", _
        Default:=dAddress, Type:=8)
    On Error GoTo 0
    
    ' Validate Source Range.
    If TypeName(srg) <> "Range" Then
        MsgBox "You canceled.", vbExclamation, "Cancel"
        Exit Sub
    End If
    
    ' Create a reference to the first cell of Destination Range.
    Dim dws As Worksheet: Set dws = ThisWorkbook.Worksheets(dName)
    Dim cOffset As Long
    cOffset = dws.Columns(dfCol).Column - dws.Columns(dlrCol).Column
    Dim dCell As Range
    Set dCell = dws.Range(dlrCol & dws.Rows.Count).End(xlUp).Offset(1, cOffset)
    
    ' Copy values, formats and formulas:
    srg.Copy dCell
    
    ' Or rather copy values only (more efficient (faster)):
    'dCell.Resize(srg.Rows.Count, srg.Columns.Count).Value = srg.Value

End Sub

【讨论】:

    猜你喜欢
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 2019-02-06
    • 1970-01-01
    相关资源
    最近更新 更多