【问题标题】:How do I duplicate rows based on cell contents (cell contains semi-colon seperated data)如何根据单元格内容复制行(单元格包含分号分隔的数据)
【发布时间】:2017-06-24 05:03:23
【问题描述】:

如何根据 B 列的内容复制行。我想为单元格中的每个“人员”单独一行?

这是我的起始表(我无法以任何其他方式提取数据):

这是我的目标:

感谢您的帮助!

【问题讨论】:

  • 您可以简单地使用自 Excel 2010 起提供的Power QueryGet and Transform 执行此操作。您只需使用该工具在分号上拆分联系人列;然后取消旋转这些列。您可能必须删除一个无关的列,并重新标记一些。如果您需要 VBA 解决方案,只需在执行时录制宏即可。

标签: excel excel-formula extra vba


【解决方案1】:

您可以实现一个循环,该循环将遍历标题下方的每一行。 在每一行中,检查 B 列中的内容并执行以下功能,该功能将根据字符“;”分割内容。

Split(Cells(row,"B"),";")

这将返回一个值数组。例如 [A 人、B 人、C 人] 现在,如果这个数组有超过 1 个值,则继续在第一个值之后为数组中的每个值插入一个新行。

Rows(row)EntireRow.Insert

祝你好运!

【讨论】:

    【解决方案2】:

    您还没有提供任何代码,所以这里有一些开始的概念:

    使用do until .cells(i,2).value = "" 循环

    使用newArray = Split(Cells(i,2).Value, ";") 得到一个数组,其中包含每个人的姓名

    使用for x = lbound(newArray) to ubound(newArray) 剪切初始行,然后插入x 次并执行cells(i+x,2).value = newArray(x).value

    最后不要忘记将ubound(newarray) 值添加到i 中,否则您将陷入寻找一个人并添加一行的无限循环中。

    【讨论】:

      【解决方案3】:

      假设您的数据在 Sheet1 中,并且需要在 Sheet2 中显示所需的输出,以下代码应该会有所帮助:

      Sub SplitCell()
          Dim cArray As Variant
          Dim cValue As String
          Dim rowIndex As Integer, strIndex As Integer, destRow As Integer
          Dim targetColumn As Integer
          Dim lastRow As Long, lastCol As Long
          Dim srcSheet As Worksheet, destSheet As Worksheet
      
          targetColumn = 2 'column with semi-colon separated data
      
          Set srcSheet = ThisWorkbook.Worksheets("Sheet1") 'sheet with data
          Set destSheet = ThisWorkbook.Worksheets("Sheet2") 'sheet where result will be displayed
      
          destRow = 0
          With srcSheet
              lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
              lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
              For rowIndex = 1 To lastRow
                  cValue = .Cells(rowIndex, targetColumn).Value 'getting the cell with semi-colon separated data
                  cArray = Split(cValue, ";") 'splitting semi-colon separated data in an array
                  For strIndex = 0 To UBound(cArray)
                      destRow = destRow + 1
                      destSheet.Cells(destRow, 1) = .Cells(rowIndex, 1)
                      destSheet.Cells(destRow, 2) = Trim(cArray(strIndex))
                      destSheet.Cells(destRow, 3) = .Cells(rowIndex, 3)
                  Next strIndex
              Next rowIndex
          End With
      End Sub
      

      【讨论】:

        猜你喜欢
        • 2021-04-14
        • 2011-03-18
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-24
        • 1970-01-01
        • 2022-12-10
        • 2019-08-07
        相关资源
        最近更新 更多