将数据复制并粘贴到excel中的其他工作表中

时间:2014-04-27 14:58:16

标签: excel vba excel-vba

我正在尝试将sheet1标签中C2:G2范围内的数据复制到sheet2标签范围C4:C8。下面是我的代码,但它只是将工作表1的单元格c2中的值重复粘贴到工作表2范围C4:C8上。你能帮忙吗?

另外,我需要将纸张1中的单元格c12的值复制到纸张2的e4,纸张1中的f12到纸张2的e5,纸张1中的i12到纸张2的e6,纸张1中的L12到e7的e7上片材2,片材1中的O12到片材2的e8上

提前致谢

安迪

Sub ticker1() 'COPY DATA FROM ROW ONE SHEET INTO A COLUMN on another sheet
Sheets("Sheet2").Range("C4:C8").Value = Sheets("Sheet1").Range("C2:G2").Value
End Sub

2 个答案:

答案 0 :(得分:0)

你的代码非常接近。事实上,它可能有效。我不确定。使用选择&激活是不可避免的问题。 Avoid it.

这不是真的答案。当你正在学习编程时,只需要一些思考。我的评论以{--

开头
Option Explicit ' {--option explicit forces you to declare your variables. Do this. Always.

Sub ticker()

    '{group your variable declarations together}
    Dim numberOfCellsToCopy As Integer
    Dim currentCopyColumn As Integer
    Dim currentPasteRow As Integer
    Dim i As Integer
    ' {--use a worksheet object instead of selecting}
    Dim srcWs As Worksheet
    Dim destWs As Worksheet

    'assign where to insert the columns
    currentCopyColumn = 2
    currentPasteColumn = 2
    numberOfCellsToCopy = 5

    ' {--Set worksheet objects}
    Set srcWs = ThisWorkbook.Worksheets("HistoricalDataRequest")
    Set destWs = ThisWorkbook.Worksheets("SomeOtherWorksheet")

    For i = 2 To numberOfCellsToCopy  'loop increases by 1??? {--YES. It does.}
        ' {--indent your code so it's easier to see program flow
        ' {--I have no idea what you're trying to do here.... sorry. You're only copying one cell
    '   --so I really can't figure what you're trying to accomplish}

        'Range(Cells(2, currentCopyColumn), Cells(2, currentCopyColumn)).Select 'number =row
        'Selection.Copy 'number =row
        'Range(Cells(7, currentPasteColumn), Cells(7, currentPasteColumn)).Select
        'ActiveSheet.Paste

        ' {--copy/paste can be done in one line using a range object
        '   --range uses a cell name.}
        srcWs.Range("B2").Copy Destination:=destWs.Range("B7")

        ' { --or more in line with your method like this}
        srcWs.Range(srcWs.Cells(2, currentCopyColumn)).Copy Destination:=destWs.Range(destWs.Cells(7, currentPasteColumn))

        'increase the column index values to go to the next one
        currentCopyColumn = currentCopyColumn + 1
        currentPasteColumn = currentPasteColumn + 4

    Next i ' {--next i will increment the i var for you}
End Sub

答案 1 :(得分:0)

根据您编辑的代码,这应该有效:

Sheets("Sheet5").Range("C4:C8").Value = Application.WorksheetFunction.Transpose(Sheets("Sheet2").Range("C2:G2").Value)

由于阵列的方向不同,转置功能会正确对齐它们。

还有其他一些方法可以做到这一点,但这可能是最直接的(如果您的范围不需要太大的灵活性)。