2016-03-01 43 views
1

我正在尝试创建一个VBA脚本,该脚本允许我选择一系列数据,然后跳过范围中的第一列,将值移动成功第一列下的列。使用VBA脚本将列移动到用户选择的范围内

Screenshot of my Excel worksheet with annotations

我需要我的剧本,让我选择一个范围。根据该范围,如果第一列不为空,则该行上其余列的值(如果它们不为null)需要复制并粘贴到行的第一列下方特殊(转置)。

我打我的大脑在最好的方式来遍历的范围内,但这里是我的脚本代码至今:

Sub ColsToRows() 

Dim rng As Range 
Set rng = Application.InputBox("Select a range", "Obtain Range Object", Type:=8) 

For Each Row In rng 
    If Not IsNull(rng.Row) Then 
     ActiveCell.Resize(1, 4).Copy 
     ActiveCell.PasteSpecial xlPasteAll, xlPasteSpecialOperationNone, SkipBlanks:=False, Transpose:=True 
    End If 
Next 

End Sub 

为什么会出现选择错误(“这个选择是无效的。 ..“)?

+0

你试过一个循环来遍历每行一次一个,复制数据,然后粘贴Special- >调换到第1列下具有相同布局的新工作表中? –

+0

如果您将所有单元格复制到原始范围之外的单个列中,它会更容易一些。 (它仍然可以按照你想要的方式完成,也许这样做更简单。)看起来你希望以特定的方式对结果进行排序,所以在你的初始循环中,只要复制在你遇到的单元格中的单元格,然后排序您想要的结果列。 – PeterT

+0

@TheGuyThatDoes'nKnowMuch我试图解决方案,至少,类似于你的建议,但我得到了我的代码运行时错误。 –

回答

0

这是最后炮制达到什么样的,我想实现的代码:

Sub PhotoColumnsToRows() 

Dim i As Long 'row counter 
Dim j As Long 'URL counter - For counting amount of URLs to add 
Dim LRow As Long 'last row 

Application.ScreenUpdating = False 'turn screen updating off to stop flickering 

LRow = Cells(Rows.Count, "A").End(xlUp).Row 'determine current last row 

i = 2 'start at row 2 

Do While i < LRow 

    If IsEmpty(Cells(i, 11)) = False Then 'checks column K for data 

     j = Application.WorksheetFunction.CountA(Range(Cells(i, 11), Cells(i, 13))) 'counts amount of Urls between K and M 

     Rows(i + 1 & ":" & i + j).Insert 'insert amount of rows found from countA 
     Range(Cells(i, 11), Cells(i, 11 + j - 1)).Copy 'copies specific range based on CountA 
     Cells(i + 1, 10).PasteSpecial Transpose:=True 'pastespecial transpose below "J" 
     Range(Cells(i, 11), Cells(i, 11 + j - 1)).ClearContents 'clear previously copied data 
     LRow = LRow + j 'increments last row by the number of rows added 


    End If 

    i = i + 1 'increment loop 
Loop 

Application.ScreenUpdating = True 'turn back on screen updating 

End Sub