简体   繁体   中英

Can I transpose a column to a row WITH spaces in Excel VBA?

I currently have an excel project that I use to sort out large sections of data in order to import that data into a specific program. I currently use this section of code in one module and call it elsewhere in my other modules.

Sub CopyTransposed(rngSource As Range, rngTargetCell As Range)

    rngTargetCell.Resize(rngSource.Columns.Count, rngSource.Rows.Count).Value = _

    Application.WorksheetFunction.Transpose(rngSource)

End Sub
-------------------------------------------------------------------------------------------
Sub Trans()

    CopyTransposed [A1:A4], [C1]

End Sub

Now I just need to figure out how to add spaces inbetween each cell. So A1 copies to C1, A2 copies to C3, and so forth.

Thank you

Join them with a double delimiter then split on a single.

Sub CopyTransposed(rngSource As Range, rngTargetCell As Range)

    Dim str As String, vals As Variant
    str = Join(Application.Transpose(rngSource), "||")
    vals = Split(str, "|")

    rngTargetCell.Resize(1, UBound(vals) + 1) = vals

End Sub

Sub Trans()

    CopyTransposed [A1:A4], [C1]

End Sub

Not sure if you always need this for rows into columns but you can use the same for columns into rows with an If statement of whether rngSource.Columns.Count > rngSource.Rows.Count.

I think you could split your solution in two phases:

1st - keep doing the transpose as now;

2nd - create a loop to move the content to the next row. Something like:

      for i = 1 to 8
          range("C" & i).EntireRow.Insert
          i = i + 1
      next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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