|
楼主 |
发表于 2023-5-4 15:59
|
显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
有劳了,不愖感激。我这里有一段代码,搞来搞去都是错的,结果是把整个表复制过去了,不知道哪里出了问题。
Sub GenerateNewTable()
Dim srcSheet As Worksheet, destSheet As Worksheet
Dim srcLastRow As Long, destLastRow As Long
Dim srcYear As Integer, destYear As Integer
Dim srcItemNum As String, destItemNum As String
Dim srcStockQty As Double, destStockQty As Double
Dim changeQty As Double
'源表与新表
Set srcSheet = ThisWorkbook.Sheets("小学数学")
Set destSheet = ThisWorkbook.Sheets.Add(After:=srcSheet)
destSheet.name = "增减记录"
' 新表第一行列标题
destSheet.Cells(1, 1) = "年份"
destSheet.Cells(1, 2) = "物品编号"
destSheet.Cells(1, 3) = "物品名称"
destSheet.Cells(1, 4) = "规格型号"
destSheet.Cells(1, 5) = "单位"
destSheet.Cells(1, 6) = "参考单价"
destSheet.Cells(1, 7) = "配备标准"
destSheet.Cells(1, 8) = "增加数量"
destSheet.Cells(1, 9) = "减少数量"
'源表与新表遍历
srcLastRow = srcSheet.Cells(Rows.count, 1).End(xlUp).Row
destLastRow = 1
For i = 4 To srcLastRow
srcYear = srcSheet.Cells(i, 1)
srcItemNum = srcSheet.Cells(i, 2)
srcStockQty = srcSheet.Cells(i, 8)
If i = 4 Or (srcItemNum <> prevItemNum) Then
destLastRow = destLastRow + 1
destYear = srcYear
destItemNum = srcItemNum
destStockQty = srcStockQty
destSheet.Cells(destLastRow, 1) = destYear
destSheet.Cells(destLastRow, 2) = destItemNum
destSheet.Cells(destLastRow, 3) = srcSheet.Cells(i, 3)
destSheet.Cells(destLastRow, 4) = srcSheet.Cells(i, 4)
destSheet.Cells(destLastRow, 5) = srcSheet.Cells(i, 5)
destSheet.Cells(destLastRow, 6) = srcSheet.Cells(i, 6)
destSheet.Cells(destLastRow, 7) = srcSheet.Cells(i, 7)
Else
changeQty = srcStockQty - destStockQty
If changeQty > 0 Then
destLastRow = destLastRow + 1
destYear = srcYear
destStockQty = srcStockQty
destSheet.Cells(destLastRow, 1) = destYear
destSheet.Cells(destLastRow, 2) = destItemNum
destSheet.Cells(destLastRow, 3) = srcSheet.Cells(i, 3)
destSheet.Cells(destLastRow, 4) = srcSheet.Cells(i, 4)
destSheet.Cells(destLastRow, 5) = srcSheet.Cells(i, 5)
destSheet.Cells(destLastRow, 6) = srcSheet.Cells(i, 6)
destSheet.Cells(destLastRow, 7) = srcSheet.Cells(i, 7)
destSheet.Cells(destLastRow, 8) = changeQty
ElseIf changeQty < 0 Then
destLastRow = destLastRow + 1
destYear = srcYear
destStockQty = srcStockQty
destSheet.Cells(destLastRow, 1) = destYear
destSheet.Cells(destLastRow, 2) = destItemNum
destSheet.Cells(destLastRow, 3) = srcSheet.Cells(i, 3)
destSheet.Cells(destLastRow, 4) = srcSheet.Cells(i, 4)
destSheet.Cells(destLastRow, 5) = srcSheet.Cells(i, 5)
destSheet.Cells(destLastRow, 6) = srcSheet.Cells(i, 6)
destSheet.Cells(destLastRow, 7) = srcSheet.Cells(i, 7)
destSheet.Cells(destLastRow, 9) = -changeQty
End If
End If
prevItemNum = srcItemNum
Next i
End Sub
|
|