2016-03-01 44 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