简体   繁体   English

VBA宏-复制数据

[英]VBA Macro - Copy Data

I am working on pulling data from cells in Sheet1 to Sheet2 and I have the correct Macro for the data copy, however, I need to have specific entries pulled based on information in another cell. 我正在将数据从Sheet1中的单元格拉到Sheet2,并且具有用于数据副本的正确宏,但是,我需要基于另一个单元格中的信息来拉特定的条目。

I am starting on cell A14 for my code and all of the work will be done in column A. Basically, I need to start at cell A14 in Sheet1 and pull every 5th cell and copy it into Sheet2 based on criteria found two cells below the cell I am determining if I need to copy or not. 我将从代码的A14单元格开始,所有工作都将在A列中完成。基本上,我需要从Sheet1的A14单元格开始,并拉出第5个单元格,并根据以下条件找到的两个单元格将其复制到Sheet2我正在确定是否需要复制的单元格。 The criteria of whether or not to copy the data from 2 cells above is if the cell contains "Choose an answer" or not. 是否从上述两个单元格复制数据的标准是该单元格是否包含“选择答案”。

For example, x+5=n If n+2="Choose and answer", copy n to Sheet2 例如,x + 5 = n如果n + 2 =“选择并回答”,则将n复制到Sheet2

The macro I have currently can be found below. 我目前拥有的宏可以在下面找到。

Sub CopyNthData()
Dim i As Long, icount As Long
Dim ilastrow As Long
Dim wsFrom As Worksheet, wsTo As Worksheet

Set wsFrom = Sheets("Sheet1")
Set wsTo = Sheets("Sheet2")
ilastrow = wsFrom.Range("A1000000").End(xlUp).Row
icount = 1

For i = 14 To ilastrow Step 5
    wsTo.Range("A" & icount) = wsFrom.Range("A" & i)
    icount = icount + 1
Next i
End Sub

Image of Sheet 工作表图片

Something like this? 像这样吗

The principle is to use Offset. 原理是使用偏移。 You can use it for the range to compare and the range to retrieve if required. 如果需要,可以将其用于要比较的范围和要检索的范围。

Given uncertainty of your comparison it seems 鉴于您比较的不确定性,看来

wsFrom.Cells(i, 1).Offset(2, 0)) = "choose an answer" 

Compares two rows above current, whereas 比较当前行上方的两行,而

wsFrom.Cells(i, 1).Offset(-2, 0)) = "choose an answer" 

Compares two rows below 比较下面两行

If you then want to copy something other than current cell, you can Offset from current cell eg 如果要复制当前单元格以外的内容,则可以从当前单元格偏移,例如

wsTo.Range("A" & icount) = wsFrom.Range("A" & i).Offset(1,0)

Example above, you then copy the value from the cell above the current. 在上面的示例中,然后从当前单元格上方的单元格中复制值。

In Offset the first number is the number of rows to move from current position and the second is the number of columns. 在“偏移”中,第一个数字是要从当前位置移动的行数,第二个是列数。

Option Explicit

Sub CopyNthData()

    Dim i As Long, icount As Long
    Dim ilastrow As Long
    Dim wsFrom As Worksheet, wsTo As Worksheet

    Set wsFrom = Sheets("Sheet1")
    Set wsTo = Sheets("Sheet2")

    ilastrow = wsFrom.Range("A1000000").End(xlUp).Row
    icount = 1

    For i = 14 To ilastrow Step 5

         If LCase$(Trim$(wsFrom.Cells(i, 1).Offset(2, 0))) = "choose an answer" Then
            wsTo.Range("A" & icount) = wsFrom.Range("A" & i)
            icount = icount + 1
        End If

    Next i
End Sub

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

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