VBA - 将字符串中的前三个字符复制到另一个单元格中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35431207/
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 10:13:47  来源:igfitidea点击:

VBA - Copy first three characters from string into another cell

excelvbaexcel-vba

提问by KevinD

I struggle with splitting the first three characters from a cell and insert them into another cell as a seperate string.

我努力从一个单元格中拆分前三个字符并将它们作为单独的字符串插入到另一个单元格中。

My (example) input:

我的(示例)输入:

A

A123456
A133457
B123456
B133457
...

What I want:

我想要的是:

A            B
A123456      A12
A133457      A13
B123456      B12
B133457      B13
...          ...

What I tried:

我试过的:

Dim ws As Worksheet
Dim cell As Range

Set ws = Worksheets("summary")

For Each cell In ws.Range("A").Cells
    cell.Value = Left(cell.Value, 3)
    Next cell

This can't work since I'd overwrite the value in all the cells A which I don't want to. Can someone provide help?

这是行不通的,因为我会覆盖我不想覆盖的所有单元格 A 中的值。有人可以提供帮助吗?

回答by GinjaNinja

in Excel without VBA, you can use formula: =LEFT(A1,3)

在没有 VBA 的 Excel 中,您可以使用公式:=LEFT(A1,3)

With VBA, you can do the following:

使用 VBA,您可以执行以下操作:

For Each cell In ws.Range("A:A").Cells
    cell.Offset(0, 1).Value = Left(cell.Value, 3)
Next cell

Note that I have amended the range. You probably want to limit is further as "A:A" will take a while.

请注意,我已经修改了范围。您可能想要进一步限制,因为“A:A”需要一段时间。

The offset function says "use the cell 1 to the right of the current cell".

offset 函数表示“使用当前单元格右侧的单元格 1”。