VBA excel编程:将数据从一个工作表转储到另一个工作表

时间:2016-01-23 14:07:17

标签: excel vba excel-vba

` 选项明确

Sub 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.

有一个带有ItemId和ItemName的Excel工作表。对于单个ItemID,有4-5个ItemName。需要使用VBA Excel编程将此工作表中的数据转储到另一个工作表中。 转储数据的工作表应在单个ItemId的不同列中列出ItemName。

1 个答案:

答案 0 :(得分: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

您应该看到您的商品放在Sheet3的不同列中(itemID = 1的列A,itemID = 2的B列,依此类推)

捕获字母数字ItemID的新例程

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

这个也应该处理字母数字代码。

相关问题