如何在 Excel 中一次转置多个单元格

如何在 Excel 中一次转置多个单元格

我有一个这样的 Excel 文档,其中有许多列表:

Name
Address
City, State
ZIP

Name
Address
City, State
ZIP

每行之间都有一个空行。我怎样才能将其转换为如下形式:

Name, Address, City, Sate, ZIP
Name, Address, City, Sate, ZIP

我做了一些研究,宏似乎会出错。特殊粘贴也只允许我逐个执行。

答案1

您不需要宏来实现这个!

只需在 Sheet2 中输入此内容并在公式中调整工作表名称:

  • A1: =OFFSET(Sheet1!$A$1,(ROW()-1)*6,0)
  • A2: =OFFSET(Sheet1!$A$1,(ROW()-1)*6+1,0)
  • A3: =OFFSET(Sheet1!$A$1,(ROW()-1)*6+2,0)
  • A4: =OFFSET(Sheet1!$A$1,(ROW()-1)*6+3,0)
  • A5: =OFFSET(Sheet1!$A$1,(ROW()-1)*6+4,0)

然后标记您刚刚创建的条目并将其向下拖动至需要的长度..完成!

答案2

我几天前回答过这个问题,但我的答案似乎被遗失了。也许我没有正确地发布它,因为我是这个网站的新手。

我从 20 世纪 70 年代末起就没再住在美国,但我们在底特律的两个地址的线路数不同。公式解决方案依赖于每个地址的线路数相同,因此我认为这不是一个合适的解决方案。

我在 Sheet1 中放置了以下英文地址。第一个是典型的英国地址。另外两个是真实的(除了名称和邮政编码),但不太常见。第二个是乡村风格的地址,房屋以名称代替编号,除了村庄名称外,还包含当地城镇。第三个地址最不寻常,因为它没有街道名称。正如地址所暗示的那样,这所房子建在曾经是 Bury St Edmunds 修道院西面的废墟上。

John Smith
5 Acacia Avenue
York
Yorkshire
YO3 2RG

Sarah Jones
Lilac Cottage
Chapel Lane
Houghton
Huntingdon
Cambridgeshire
CB12 4TG

Alice Green
1 The West Front
Abbey Ruins
Bury St Edmunds
IP33 1RS

下面的宏将按照您想要的样式将这些地址复制到 Sheet2 中。

Sub Test2()

  Dim Col1Crnt As Integer
  Dim Col1Max As Integer
  Dim Col2Crnt As Integer
  Dim Sheet1() As Variant
  Dim Row1Crnt As Integer
  Dim Row1Max As Integer
  Dim Row2Crnt As Integer

  With Sheets("Sheet1")
    ' Find the last used row in Sheet1
    Row1Max = .Cells.Find("*", .Range("A1"), xlFormulas, _
                                            , xlByRows, xlPrevious).Row
    ' Load column 1 to Sheet1.
    Sheet1 = .Range(.Cells(1, 1), .Cells(Row1Max, 1)).Value
    ' Although I am only loading one column, Sheet 1 will be a 2D array
    ' with the row as the first dimension and the column as the second.
    ' I have loaded Sheet1 to an array because switching between
    '  worksheets is very slow.
  End With

  With Sheets("Sheet2")
    Row2Crnt = 1
    Col2Crnt = 1
    For Row1Crnt = 1 To Row1Max
      If Sheet1(Row1Crnt, 1) = "" Then
        ' blank line
        If Col2Crnt <> 1 Then
          ' Only advance row for first blank row
          Row2Crnt = Row2Crnt + 1
          Col2Crnt = 1
        End If
      Else
        .Cells(Row2Crnt, Col2Crnt).Value = Sheet1(Row1Crnt, 1)
        Col2Crnt = Col2Crnt + 1
      End If
    Next
  End With

End Sub

希望这可以帮助

相关内容