2013-06-04 37 views
0

嗨我寫下面的代碼將一個工作表中某些範圍的單元複製到另一個名爲 「Report」的表中。VBA代碼將數據從多個工作表複製到另一個工作表所需的指導

Sub sample() 

Dim lastRow As Long 
Dim col As Long 
Dim a As String, b As String, c As String 

With Sheets("Jack") 
lastRow = .Range("A" & Rows.Count).End(xlUp).Row 

If lastRow < 4 Then lastRow = 4 

For i = 5 To lastRow 
For col = 2 To 31 
If .Cells(i, col) <> "" Then 

a = .Cells(1, 2) 
b = .Cells(i, 1) 
c = .Cells(i, col) 
d = .Cells(3, col) 

With Sheets("Report") 
.Range("A" & .Range("A" & .Rows.Count).End(xlUp).Row + 1).Value = a 
.Range("B" & .Range("B" & .Rows.Count).End(xlUp).Row + 1).Value = b 
.Range("C" & .Range("C" & .Rows.Count).End(xlUp).Row + 1).Value = c 
.Range("D" & .Range("D" & .Rows.Count).End(xlUp).Row + 1).Value = d 
End With 
End If 
Next 
Next 

End With 
End Sub 

上面的代碼工作完全從一個工作表命名爲「傑克」複製數據,但我想從其他工作表中的數據也是如此。總共有10張工作表,我想將sheet2中的數據複製到sheet7,並希望跳過sheet1,sheet8,9和10. 任何有關從所選工作表複製數據的循環都將非常感謝。 謝謝

回答

1

如果所有的數據是一樣的,那麼它應該是爲更換您的

With Sheets("Jack") 

隨着

For x = 2 To 7 

With Sheets(x) 

而且增加一個緊鄰結尾一樣簡單。

所以完整的代碼看起來像:

Sub sample() 


Dim lastRow As Long 
Dim col As Long 
Dim a As String, b As String, c As String 

For x = 2 To 7 

With Sheets(x) 

lastRow = .Range("A" & Rows.Count).End(xlUp).Row 

If lastRow < 4 Then lastRow = 4 

For i = 5 To lastRow 
For col = 2 To 31 
If .Cells(i, col) <> "" Then 

a = .Cells(1, 2) 
b = .Cells(i, 1) 
c = .Cells(i, col) 
d = .Cells(3, col) 

With Sheets("Report") 
.Range("A" & .Range("A" & .Rows.Count).End(xlUp).Row + 1).Value = a 
.Range("B" & .Range("B" & .Rows.Count).End(xlUp).Row + 1).Value = b 
.Range("C" & .Range("C" & .Rows.Count).End(xlUp).Row + 1).Value = c 
.Range("D" & .Range("D" & .Rows.Count).End(xlUp).Row + 1).Value = d 
End With 
End If 
Next 
Next 

End With 
Next x 

End Sub 
+0

太感謝你了,我剛申請,它是工作。真的非常感謝你的努力和投入,它很難找到要說謝謝的話。我只有一個問題,是否可以根據「Value = B」的行數合併「Value = a」。希望這兩張圖片有助於正確理解這個問題[鏈接](http://i40.tinypic.com/n5juxv.jpg)和[鏈接]((http://i40.tinypic.com/fxth03.jpg)) – OMK28

+0

您可以使用.merge方法:'Range(xlcell,xlcell.offset(1,0))。Merge'。你可以通過遍歷它來返回地址('對於xlRange中的每個xlCell |如果xlCell.value像valFind那樣| flg = true | strAddresses = strAddresses + xlcell.address | elseif flg = true,然後退出| end if')您可能希望保證搜索是通過降序行完成的,您可以使用行偏移和'for i = start to finish'循環 – Orphid

相關問題