VBA 复制粘贴到单元格中的行/列号

问题描述 投票:0回答:1

我正在尝试从 Book1 复制某些值并粘贴到 Book2 中的特定(更改)位置。由于该位置预计会发生变化,因此我想根据现有单元格中的行/列号进行粘贴。我是 VBA 新手,不知道如何循环它。任何想法都非常感激,谢谢!

我尝试了下面的方法,但我正在考虑以某种方式将硬编码值转换为变量

Windows("Book1.xlsm").Activate
    Range("G6:G10").Select
    Selection.Copy
    Windows("Book2.xlsx").Activate
    Range("FC8").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
excel vba variables copy paste
1个回答
1
投票

通过赋值复制值

Option Explicit

Sub CopyValues()
    
    ' Source
    Const swbName As String = "Book1.xlsm"
    Const swsName As String = "Sheet1"
    Const srgAddress As String = "G6:G10"
    ' Destination
    Const dwbName As String = "Book2.xlsx"
    Const dwsName As String = "Sheet1"
    Const dfCellAddress As String = "FC8"
    
    ' Source
    Dim swb As Workbook: Set swb = Workbooks(swbName)
    ' if the source workbook is the workbook containing this code, instead, use:
    'Dim swb As Workbook: Set swb = ThisWorkbook
    Dim sws As Worksheet: Set sws = swb.Worksheets(swsName)
    Dim srg As Range: Set srg = sws.Range(srgAddress)
    
    ' Destination
    Dim dwb As Workbook: Set dwb = Workbooks(dwbName)
    Dim dws As Worksheet: Set dws = dwb.Worksheets(dwsName)
    Dim dCell As Range: Set dCell = dws.Range(dfCellAddress)
    ' If the destination is to be dynamic, i.e. the data should be appended
    ' after the last row containing data, instead, use something like this:
'    With dws.Range(dfCellAddress)
'        Set dCell = dws.Cells(dws.Rows.Count, .Column).End(xlUp) ' last cell
'        If dCell.Row < .Row Then
'            Set dCell = .Cells ' use the given cell
'        Else
'            Set dCell = dfCell.Offset(1) ' use the cell below the last cell
'        End If
'    End With
    Dim drg As Range: Set drg = dCell.Resize(srg.Rows.Count)
    ' The previous line is short for the following...
    'Set drg = dCell.Resize(srg.Rows.Count, srg.Columns.Count)
    ' ... and can be used since only one column is being copied.
    
    ' Copy.
    drg.Value = srg.Value
    
    ' Inform.
    MsgBox "Values copied.", vbInformation
    
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.