简体   繁体   English

Excel VBA循环遍历用空格隔开的文本部分,然后复制并转置到新工作表上

[英]Excel VBA Loop through sections of texts separated by blank space then copy and transpose onto a new sheet

I will like code that can cycle through a worksheet and copy and transpose each section onto another worksheet. 我希望可以循环工作表并将每个部分复制并转置到另一个工作表中的代码。

I have code that uses SpecialCells but have had issues with it. 我有使用SpecialCells的代码,但是有问题。 I would prefer code that uses Shift+Down then Shift+Right .End(xlDown) .End(xlToRight) . 我更喜欢使用Shift + Down然后Shift + Right .End(xlDown) .End(xlToRight)

Here is the code that worked but I had issues when there were blanks in any of the cells. 这是有效的代码,但是当任何单元格中都有空格时,我遇到了问题。 This code copies each area, only need column B and column C then pastes it into worksheet CombinedAndTransposed 此代码复制每个区域,只需要B列和C列,然后将其粘贴到工作表CombinedAndTransposed

    Sub Copy_Transpose_All_Sections()
    Dim Ra As Range

    Application.ScreenUpdating = False
    'B:C 2nd And 3rd Columns to copy
    For Each Ra In Columns("B:C").SpecialCells(xlCellTypeConstants, 23).Areas '23
        Ra.Copy
        Worksheets("CombinedAndTransposed").Cells(Rows.count, "B").End(xlUp).Offset(1, 0).PasteSpecial Transpose:=True
    Next Ra
    Application.CutCopyMode = False
End Sub 

The data is in the 2nd and 3rd column and is separated with blank rows. 数据在第二列和第三列中,并用空白行分隔。

The result should take each section of text and transpose it. 结果应采用文本的每个部分并进行转置。

My code above works only when there is data in all cells within a section, but fails if any are missing or any formatting of the cells change. 我上面的代码仅在某节中所有单元格中都有数据时才有效,但是如果缺少任何数据或单元格的任何格式更改都将失败。

This is much more efficient. 这样效率更高。

Private Sub Answer ()
    With Worksheets("Sheet1")
        Dim source As Range
        Set source = .Range("B1", .Range("C" & Rows.Count).End(xlUp))
    End With

    With Worksheets("Sheet2")
        Dim destination As Range
        Set destination = .Range("B1")
    End With

    ' Loop every odd row in range.
    Dim row As Long
    For row = 1 To source.Rows.Count Step 2
        ' Must resize destination range to match source. Transpose data from row to column.
        destination.Resize(source.Rows(row).Cells.Count).Value = Application.Transpose(source.Rows(row))
        ' Set destination to offset with a gap between data.
        Set destination = destination.Offset(destination.Cells.Count + 2)
    Next row
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM