2017-04-20 62 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