2015-06-03 81 views
0

我需要複製數據,但由於需要複製的數據量相當大,並且需要手動填充,所以我想通過使用宏來實現。我不明白數組是如何工作的。用於複製的陣列

這給了我適量的副本,但只有最後一個我需要複製的單元格。

Sub copyer() 

Dim fromH As Integer 'fromheight 
Dim fromW As Integer 'fromwidth 

Dim toH As Integer  'to height 
Dim toW As Integer  'to width 

Dim counter As Integer 
counter = Worksheets("blad1").Range("D3").Value 'amount of filled-in data lines to copy 

Dim Times As Integer 'number of times to run the loop, depending on the filled in data 
Times = counter + 1 

Dim tostart As Integer 'location where to start placing the data 
         'depending on how much data is already present 
Dim toend As Integer 'location up to where to place 

tostart = Sheets("blad2").Range("L1").Value + 1 '(+2 if theres a header) 
toend = tostart + counter 

Dim Copy As Integer 

For Copy = 1 To Times 
For toH = tostart To toend 
    For toW = 1 To 2 
     For fromH = 12 To 22 Step 2 
      For fromW = 1 To 26 Step 25 
       Sheets("blad2").Cells(toH, toW).Value = _ 
       Sheets("blad1").Cells(fromH, fromW).Value 
      Next fromW 
     Next fromH 
    Next toW 
Next toH 
Next Copy 

'this macro needs to copy the data 

'from blad1 
'from height 12 to 22 (steps of 2)(10 times) 
'from width 1 and 26 (not the cells inbetween) 

'to blad2 
'to height depending on the data present (dim tostart)'till height needed (steps of 1) 
'to width 1 and 2 

'blad1, D3 holds the input-datacounter 
'blad2, L1 holds the output-datacounter 

End Sub 
+0

這不是真的清楚你要什麼做。看起來過於複雜,你會有一個5x嵌套的'For'循環。您是否已經使用F8逐步完成代碼,手動完成整個流程,並查看它與期望的差異?如果沒有,那應該是你調試的第一步。 –

+0

我的答案[這裏](http://stackoverflow.com/questions/14035772/how-to-assign-an-excel-range-to-a-2d-array/14060707#14060707)應該可以幫助你複製範圍來回陣列。 – SeanC

回答

0

正如Zemens所提到的那樣,您真的過於複雜了!要在數組中進行復制,只需要與數組中的維數一樣多的循環。所以在這種情況下兩個!我使用了一些簡單的算術從一張紙轉換到另一張紙。它可能不完美,但希望能讓你開始!

Dim intRowLoop As Integer, intColLoop As Integer 

For intRowLoop = tostart To toend 
    For intColLoop = 1 To 2 
     Sheets("blad2").Cells(intRowLoop, intColLoop).Value = _ 
      Sheets("blad1").Cells(12 + ((intRowLoop - tostart) * 2), fromW * 26).Value 
    Next intColLoop 
Next intRowLoop 
0

最後我去了;

(在sheetnames是不同勢,如上圖所示是一個測試,以得到它的工作)

(yust了最重要的一點)

For ToH = tostart To toend Step 2 
For ToW = 2 To 8 Step 6 
     Sheets("factuur2").Cells(ToH, ToW).Value = _ 
     Sheets("multiprijs").Cells(FromH, FromW).Value 
    FromW = 28 
Next ToW 
FromH = FromH + 2 
ToW = 2 
FromW = 5 
Next ToH 

但是我有這種方法的問題是,這裏的「寬度」變量只能保存2個值;

Width + something 'or 
Width to something 'at a regular interval 

我想,使這種面向未來的寬度是; 1,3,5,19,什麼

兩者的距離和到寬

泰都幫助我得到這個權利雖然:)