2016-01-23 29 views
-3

` Explicit選項VBA Excel規劃:傾倒從一個片的數據到另一個片

子MoveToSheet() 範圍。( 「A2:A9」)選擇

If Range("A2:A9").Value = "1" Then 

Sheets("Sheet1").Range("B2:B9").Copy Destination:=Sheets("Sheet3").Range("A2:A9") 

Do 
    ActiveCell.Offset(1, 0).Select 
Loop 
End If 

結束子`output sheet

The sheet from which data has to be dumped.

有一個excel工作表項目Id與和ItemName.For單個的ItemID有4-5 ItemName。需要使用VBA Excel編程將此工作表中的數據轉儲到另一個工作表中。 轉儲數據的工作表應在單個ItemId的不同列中列出ItemName。

+2

SO不是我的網站的代碼。請展示您的嘗試並解釋發生了什麼問題,因此我們可能會解決代碼中的特定問題。 –

+0

您可以檢查代碼。昨天開始使用這種技術,所以不太瞭解。代碼說有類型不匹配錯誤:( – Sunaina

回答

0

由於您試圖從單元格範圍Range("A2:A9").Value中獲取值,因此會出現類型不匹配錯誤,我認爲此語法僅適用於單個單元格,如Range("A2").Value。然後你有一個Do...Loop這將循環,直到spreasheet的最後一行,因爲沒有條件檢查。

請你試試這個子程序嗎?你可以把它放在一個模塊中,並從VBA編輯器調用它或將它鏈接到一個按鈕。我假設你的物品按itemID排序。

Sub copyItems() 
    Sheets("Sheet1").Activate 

    ' This will clear your destination worksheet. Change the range to your needs 
    Sheets("Sheet3").Range("A2:Z999").ClearContents 

    Dim itemID As Integer, startRow As Integer, endRow As Integer 
    startRow = 2 

    Do 
    itemID = Sheets("Sheet1").Cells(startRow, 1) 
    endRow = startRow + WorksheetFunction.CountIf(Sheets("Sheet1").Range("A:A"), itemID) - 1 
    Sheets("Sheet3").Range("A2:A" & endRow - startRow + 2).Offset(0, itemID - 1).Value = _ 
     Sheets("Sheet1").Range("B" & startRow & ":B" & endRow).Value 
    startRow = endRow + 1 
    Loop While Cells(startRow, 1).Value <> "" 
End Sub 

你應該看到您的物品擺放在不同的列在表Sheet 3

新程序(用於項目Id = 1,對項目Id = 2列B等列A)趕上字母ItemIDs

Sub copyItems2() 
    Dim itemID As String, startRow As Integer, endRow As Integer, itemNum As Integer 
    Dim source As String, destination As String 

    startRow = 2 
    itemNum = 1 
    source = "Sheet1" 
    destination = "Sheet3" 

    Sheets(source).Activate 

    ' This will clear your destination worksheet. Change the range to your needs 
    Sheets(destination).Range("A2:Z999").ClearContents 

    Do 
    itemID = Sheets(source).Cells(startRow, 1) 
    endRow = startRow + WorksheetFunction.CountIf(Sheets(source).Range("A:A"), itemID) - 1 
    Sheets(destination).Range("A2:A" & endRow - startRow + 2).Offset(0, itemNum - 1).Value = _ 
     Sheets(source).Range("B" & startRow & ":B" & endRow).Value 
    startRow = endRow + 1 
    itemNum = itemNum + 1 
    Loop While Cells(startRow, 1).Value <> "" 
End Sub 

這一個應該也處理字母數字代碼。

+0

雅它工作正常:) Thankyou這麼多。但是當我在這行代碼(Sheets(「Sheet3」)。Range(「A2:Z999」)。ClearContents)中將Sheet3更改爲Sheet4時,它顯示錯誤「Subscript out of range」。 – Sunaina

+0

提交您發佈的代碼我認爲Sheet1是源工作表,Sheet3是目標工作表。請,你能告訴我他們叫什麼嗎?如果我嘗試在電子表格中更改它,我會得到相同的錯誤,但是我沒有Sheet4在那裏... – grab74

+0

另外,我想知道如果itemId是像「AS_100」INSTEAD OF「1」這樣的字符串。增量的東西會起作用嗎? :O – Sunaina

相關問題