由於您試圖從單元格範圍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
這一個應該也處理字母數字代碼。
SO不是我的網站的代碼。請展示您的嘗試並解釋發生了什麼問題,因此我們可能會解決代碼中的特定問題。 –
您可以檢查代碼。昨天開始使用這種技術,所以不太瞭解。代碼說有類型不匹配錯誤:( – Sunaina