简体   繁体   中英

Excel 2010 VBA step through a string and place one char into each cell in sequence

I am used to string slicing in 'C' many, many years ago but I am trying to work with VBA for this specific task.

Right now I have created a string "this is a string" and created a new workbook.

What I need now is to use string slicing to put 't' in, say, A1, 'h' in A2, 'i' in A3 etc. to the end of the string.

After which my next string will go in, say B1 etc. until all strings are sliced.

I have searched but it seems most people want to do it the other way around (concatenating a range).

Any thoughts?

Use the mid function.

=MID($A$1,1,1)

The second argument is the start position so you could replace that for something like the row or col function so you can drag the formula dynamically.

ie.

=MID($A$1,ROW(),1)

If you wanted to do it purely in VBA, I believe the mid function exists in there too, so just loop through the string.

Dim str as String
str = Sheet1.Cells(1,1).Value

for i = 1 to Len(str)
    'output string 1 character at a time in column C
    sheet1.cells(i,3).value = Mid(str,i,1)
next i

* edit *

If you want to do this with multiple strings from an array, you could use something like:

Dim str(1 to 2) as String
str(1) = "This is a test string"
str(2) = "Some more test text"

for j = Lbound(str) to Ubound(str)
    for i = 1 to Len(str(j))
        'output strings 1 character at a time in columns A and B
        sheet1.cells(i,j).value = Mid(str(j),i,1)
    next i
next j

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