簡體   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