繁体   English   中英

Excel 使用 VBA 将单元格数据从一张纸复制到另一张纸

[英]Excel Copy Cell Data from one sheet to another using VBA

我是 VBA 的新手,我必须将单元格值从一张纸复制到另一张纸。 现有的代码是

'go to the team sheet and select col 3-5 on last row and copy
    Sheets(strname).Activate
    ActiveCell.Offset(0, -10).Select
    Range(ActiveCell, Cells(ActiveCell.Row, ActiveCell.Column + 2)).Select
    Selection.Copy
    DoEvents
    'select the col 2 on team line and paste
    Sheets("dtl overview").Select
    ActiveCell.Offset(0, -6).Select
    ActiveSheet.paste Link:=True
    DoEvents
    

问题是,我在“团队”表中又添加了一列。 所以上面的复制脚本必须向后读取一个单元格。

例如,上面的代码正在从 D、E 和 F 单元格中读取数据。 我不知道怎么...

我正在寻找更改上述代码以从 C,D&E 读取值。

欢迎输入并高度评价!

我也不知道您如何始终使用该代码从D:F列复制。
您的代码的作用是:

'Activate sheet indicated in the "strname" variable.
'"strName" must be set elsewhere in the code?
Sheets(strname).Activate

'When the sheet is activated a cell will already be selected on there.
'This will be whatever cell was active when the sheet was previously looked at.
'This could easily change if a user selects another cell.

'The "OFFSET" command looks at the same row and ten columns to the left of the ActiveCell.
'If the ActiveCell is not in at least column J (11th column) then this
'will throw an "Application defined or Object Defined error" as it will try and select
'a column before column A.
'The offset cell is then selected - hopefully it will be column D.
ActiveCell.Offset(0, -10).Select

'This will select a range from the ActiveCell plus 2 columns on the same row.
'Hopefully columns D:F
Range(ActiveCell, Cells(ActiveCell.Row, ActiveCell.Column + 2)).Select

'Copy the selection.
Selection.Copy

'Don't need this line unless other code you haven't included needs it.
DoEvents

'Select the "dtl overview" sheet.
Sheets("dtl overview").Select

'Again, whichever cell was last active on "dtl overview" and select the cell 6 columns to the left.
ActiveCell.Offset(0, -6).Select

'Paste a link to the original cells.
'So if you copied D4:F4 on the original sheet (which I'll call "Sheet1") then this will paste
'=Sheet1!D4 , =Sheet1!E4 and =Sheet1!F4
ActiveSheet.Paste Link:=True

'Definitely shouldn't need this now.
DoEvents

目前,您的代码在当前处于活动状态的单元格的左侧看起来有 10 列 - 因此取决于您在运行代码时选择了哪个单元格。

您没有说要复制哪一行,因此此代码复制第 1 行并粘贴到单元格D1

Sub Test()

    Dim strName As String
    strName = "Sheet1"
    
    'ThisWorkbook means the file containing this code.
    Dim wrkSht As Worksheet
    Set wrkSht = ThisWorkbook.Worksheets(strName)
    
    'Cells(1,4) is row 1, column 4.
    'Range(Cells, Cells) shows a start & end cell for the range.
    With wrkSht
        .Range(.Cells(1, 4), .Cells(1, 6)).Copy _
            Destination:=ThisWorkbook.Worksheets("dtl overview").Cells(1, 4)
    End With
    
End Sub

延伸阅读:

暂无
暂无

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

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