Excel 2010 VBA 单步执行字符串并按顺序将一个字符放入每个单元格中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13778819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:34:15  来源:igfitidea点击:

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

stringexcel-vbavbaexcel

提问by Cimbian

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

许多年前,我习惯于在“C”中进行字符串切片,但我正在尝试使用 VBA 来完成这项特定任务。

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.

我现在需要的是使用字符串切片将 't' 放入 A1、A2 中的 'h'、A3 中的 'i' 等到字符串的末尾。

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

之后我的下一个字符串将进入,比如 B1 等,直到所有字符串都被切片。

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

我已经搜索过,但似乎大多数人都想反过来做(连接一个范围)。

Any thoughts?

有什么想法吗?

回答by Sam

Use the mid function.

使用中音功能。

=MID($A,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.

第二个参数是起始位置,因此您可以将其替换为 row 或 col 函数之类的内容,以便您可以动态拖动公式。

ie.

IE。

=MID($A,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.

如果您想纯粹在 VBA 中执行此操作,我相信 mid 函数也存在于其中,因此只需循环遍历字符串即可。

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