2017-04-20 94 views
0

我已經創建了下面的宏Excel宏單列轉兩列

我的數據會一路在主數據表中排3710 - 我不知道該怎麼這個宏強制循環和包括所有數據

Sub Macro3() 
' 
' Macro3 Macro 
' 

' 
    Range("A1:A2").Select 
    Selection.Copy 
    Sheets("Sheet2").Select 
    Range("A1:B1").Select 
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _ 
     False, Transpose:=True 
    Sheets("Sheet1").Select 
    Range("A3:A4").Select 
    Application.CutCopyMode = False 
    Selection.Copy 
    Sheets("Sheet2").Select 
    Range("A2:B2").Select 
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _ 
    False, Transpose:=True 
End Sub 
+0

所以,你要採取在Sheet1中A1的值:A3710,放在Sheet2中和表2的B列每隔值的列中的所有其他價值? –

回答

0

您可以使用for循環做到這一點。複製/粘貼也是我們通常在VBA以及.SELECT.ACtivate中避而遠之的。這些都是一個人完成的功能,但計算機可以只設置細胞等於像其他單元格的值:

Sheets("Sheet1").Cells(1, 1).value = Sheets("Sheet2").Cells(1,1).value 

它說在Sheet1中單元格「A1」應設置爲任何值在Sheet2的單元格「A1 」。

改變周圍的事物,實現一個循環來執行你的轉置,並使用一些簡單的線性迴歸公式來確定寫這行,我們得到:

Sub wierdTranspose() 
    'Loop from row 1 to row 3710, but every other row 
    For i = 1 to 3710 Step 2  
     'Now we select from row i and row i + 1 (A1 and A2, then A3 and A4, etc) 
     'And we put that value in the row of sheet2 that corresponds to (.5*i)+.5 
     ' So if we are picking up from Rows 7 and 8, "i" will be 7 and (.5*i)+.5 will be row 4 that we paste to 
     ' Then the next iteration will be row 9 and 10, so "i" will be 9 and (.5*i)+.5 will be row 5 that we paste to 
     ' and on and on until we hit 3709 and 3710... 
     Sheets("Sheet2").Cells((.5*i)+.5, 1).value = Sheets("Sheet1").Cells(i, 1).value 
     Sheets("Sheet2").Cells((.5*i)+.5, 2).value = Sheets("Sheet1").Cells(i+1, 1).value 
    Next i 
End Sub 
0

批量數據通過VBA陣列最好的轉移,與不需要複製/粘貼。

事情是這樣的:

Sub SplitColumn() 
    Dim A As Variant, B As Variant 
    Dim i As Long 
    Dim ws1 As Worksheet, ws2 As Worksheet 

    Set ws1 = Sheets(1) 
    Set ws2 = Sheets(2) 

    With ws1 
     A = .Range(.Cells(1, 1), .Cells(3710, 1)) 
    End With 

    ReDim B(1 To 1855, 1 To 2) 
    For i = 1 To 1855 
     B(i, 1) = A(2 * i - 1, 1) 
     B(i, 2) = A(2 * i, 1) 
    Next i 

    With ws2 
     .Range(.Cells(1, 1), .Cells(1855, 2)).Value = B 
    End With 

End Sub