2012-09-18 54 views
2

我放棄。我花了四個小時試圖弄清楚爲什麼這個宏不起作用。 我希望它採用給定的源範圍,使用For循環遍歷它並將值複製到不同的列。循環插入行,複製數據

我希望它在給定的目標細胞開始,

  • 輸入值
  • 創建使用插入新行(整行,而不只是插入該列。我想,以適應數據在現有的一組行中)
  • 不覆蓋指定目標列終點的標記。有下面的數據需要保存。

我不能找出爲什麼

  • 在程序的一個實例,它進入的價值,但然後劃出該數據作爲它插入的下一行。
  • 在第二種情況下,它會跳過一行,並抹殺列標記

請注意,我不是在尋找到問題的聰明,優雅的解決方案,結束在努力教自己的範式,我想保持事情真正的基礎。隨着我對基礎知識的瞭解越來越多,我會嘗試一些高級技巧。

TIA

Sub Macro1() 
Dim firstRow As Range, lastRow As Range 
Dim source As Range, destination As Range 
Dim readCell As Range 

Set firstRow = Range("F2") 
Set lastRow = Range("F20") 
Set destination = Range("A21") 


Set source = Range(firstRow.Address(False, False) & ":" & lastRow.Address(False, False)) 

For Each readCell In source 
    destination.Select 
    destination.Value = readCell.Value 

    If (readCell.Address(False, False) = lastRow.Offset(1, 0)) Then 
     Exit For 
    Else 
     'destination.Select 
    End If 

    'MsgBox (destination.Value) 
    destination.EntireRow.Insert Shift:=xlUp 
    Set destination = destination.Offset(1, 0) 
Next 
End Sub 

回答

1

下面是一些提示:

鑑於firstRowlastRow是單細胞,不需要的東西Address。使用

Set source = Range(firstRow, lastRow) 

destination.EntireRow.Insert Shift:=xlUp,因爲你申請Insert到整個行,Shift沒什麼區別。使用

destination.EntireRow.Insert 

插入行中放置上述destination,和destination向下偏移。所以for循環的第一次迭代這是否

  1. 設置destinationA21
  2. 插入行,轉移destinationA22
  3. 設置desination下移一行,即A23

下一次迭代會覆蓋原來的數據A22,現在在A23

我想你想

Sub Macro1() 
    Dim firstRow As Range, lastRow As Range 
    Dim destination As Range 
    Dim readCell As Range 

    Set firstRow = Range("F2") 
    Set lastRow = Range("F20") 
    Set destination = Range("A21") 

    For Each readCell In Range(firstRow, lastRow) 
     destination.Value = readCell.Value 
     destination.EntireRow.Offset(1, 0).Insert 
     Set destination = destination.Offset(1, 0) 
    Next 
End Sub 
+0

感謝。 我不明白爲什麼這麼難以識別。 我的編程錯誤總是非常簡單。 –

1

很值得稱道的,你想了解以及解決

更容易使用比增量行計數從一個固定的目的地。這種微調

  • 避免Select
  • 使用計數器,lngRow,控制新行和新的價值觀

    code

    Sub Macro1() 
    Dim readCell As Range 
    Dim lngRow As Long 
    For Each readCell In Range("F2:F20") 
        [a21].Offset(lngRow, 0).EntireRow.Insert Shift:=xlUp 
        [a21].Offset(lngRow, 0).Value = readCell.Value 
        lngRow = lngRow + 1 
    Next 
    End Sub 
    
+0

呵呵! 這很有趣。 使用select有一些開銷嗎? 謝謝 –

+0

@KenIngram是的。它增加了時間,並且在某些情況下可能導致錯誤,或觸發進一步的宏事件。我進一步整理了我的代碼,以保持您的循環完好無損,但刪除了不必要的範圍位置 – brettdj