简体   繁体   中英

VBA - Copy and Paste Dynamic Range with Dynamic Start Point

I am very new to the VBA community and usage so my illiteracy is a bit embarrassing. I work in a lab that routinely deals with very large data output files. In order to statistically analyze these data files we often have to rearrange the output data into a more statistically friendly format. Therein lies my problem.

I have created and VBA that does this for a very specific dataset, copying and paste transposing 5 data points at a time. I would like help in creating something that allows me to have a more generic approach to this where I might be able to enter the number of study time points (typically between 3 and 10) and the number of study participants (between 10 and 100) and still get the copy/paste transpose done on the correct sheet.

What I have in my specific VBA is below. I basically have this done manually all the way to a range of B208:212 and all the way through Sheet 13.

Sheets("Raw Data").Select
Range("B3:B7").Select
Selection.Copy
Sheets("Sheet1").Select
Range("D2").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
    False, Transpose:=True 

What this does is copies five data points for one study participant, goes to my desired sheet, and paste transposes in the row corresponding with my study participant. I need to do this for up 100 study participants, each beginning on its own row starting with D2.

Sorry this is confusing. I am working on posting more clarification below.

Sheets("Raw Data").Select
Range("B3:B7").Select
Selection.Copy
Sheets("Sheet1").Select
Range("D2").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
    False, Transpose:=True 

reduces to

Sheets("Sheet1").Range("D2").Resize(5, 1).Value = _
 Application.Transpose(Sheets("Raw Data").Range("B3").Resize(1, 5).Value)

Taking that as a starting point, you can declare some variables (or better, use Constants) for the "5", etc, but you'd need to add some more details to your question, including what dtermines where the next "paste" point is. you mention multiple sheets but it's not clear how those are involved in the operation.

Eg:

Sub Tester()

    Const DATA_PTS As Long = 5

    Dim rngCopy As Range, rngPaste As Range

    'start point for source data
    Set rngCopy = Sheets("Raw Data").Range("B3").Resize(DATA_PTS, 1).Value

    Do While Application.CountA(rngCopy) > 0

        'Set rngPaste = ? 'what determines where data is copied to?

        rngPaste.Resize(1, DATA_PTS).Value = _
           Application.Transpose(rngCopy.Value)

        'next source range
        Set rngCopy = rngCopy.Offset(DATA_PTS, 0)
    Loop

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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