2016-08-01 48 views
0

我的宏的目標太簡單,只複製其中包含值1的任何行的單元格,並將相同的值插入右上方的另一行中。唯一需要注意的是我在列B & C中也有值,所以我希望複製和插入這些值。我的宏是低於Excel VBA插入複製的單元格語法

我已經認識到,問題是優秀的是採取列AR相對於範圍AR,但我有點麻煩繞過這一點,因爲我不能想到命名我的R變量另一種方式繞過這個問題。

非常感謝您的幫助!

Sub BlankLine() 

    Dim Col As Variant 
    Dim BlankRows As Long 
    Dim LastRow As Long 
    Dim R As Long 
    Dim StartRow As Long 

    Col = "A" 
    StartRow = 1 
    BlankRows = 1 

    LastRow = Cells(Rows.Count, Col).End(xlUp).Row 

    Application.ScreenUpdating = False 

    With ActiveSheet 
     For R = LastRow To StartRow + 1 Step -1 
      If .Cells(R, Col) = "1" Then 
       .Range("AR:CR").Copy 
       Selection.Insert Shift:=xlDown 
      End If 
     Next R 
    End With 
    Application.ScreenUpdating = True 

End Sub 
+0

你是什麼意思的範圍AR? AR是excel中列的定義。 –

+0

你是對的,我對此感到抱歉。我現在有點心慌意亂,並且意識到我寫的東西是愚蠢的。 Danesjai雖然解決了它。他的代碼拷貝每一行a中有一個1的行,並將其插入到正上方的新行中(限制複製的行以僅包含具有實際值的單元格) –

回答

1

更新時間:我改變了代碼,只是複製這些三列(A至C),然後插入新行,然後設置的值,以這三個列。評論在代碼中。如果要複製多個列,只是改變了整在dupRange變量(即,在.Cells(R, Col + 2))的)

Sub BlankLines() 

Dim Col As Integer 
Dim BlankRows As Long 
Dim LastRow As Long 
Dim R As Long 
Dim StartRow As Long 

Col = 1 'changed to number 
StartRow = 2 'changed to 2 since you have a header 
BlankRows = 1 'not used in this code... 

LastRow = Cells(Rows.Count, Col).End(xlUp).Row 

Application.ScreenUpdating = False 

With ActiveSheet 
    For R = LastRow To StartRow Step -1 
     If .Cells(R, Col) = "1" Then 
      Dim dupRange As Variant 'array to store values 
      Set dupRange = .Range(.Cells(R, Col), .Cells(R, Col + 2)) 'store the column values for the row 
      .Rows(R & ":" & R).Insert Shift:=xlDown 'insert the new row 
      c = 0 'to increment over the copied columns 
      For Each v In dupRange 
       .Cells(R, Col + c) = v 'sets the array values to each column 
       c = c + 1 
      Next v 
     End If 
    Next R 
End With 

Application.ScreenUpdating = True 

End Sub 

試試這個。不是100%確定這是否是你想要的。

+0

令人驚訝的是我正在尋找的東西。非常感謝Daneshjai!你的整個代碼是完美的,除了我的目的,我做了我的startrow = 2:D再次感謝! –

+0

道歉,但我只需要一點點的幫助。您的代碼複製整行。如果我說我在其他列中的值是否有任何方法複製說每列僅列a-c的值? –

+0

更新了代碼。應該做你現在正在尋找的東西。 – daneshjai

相關問題