[英]Insert square brackets around some text in a cell using Excel VBA
Is it possible to insert square brackets around some text in a cell with Excel VBA code, where there is none? 是否可以在没有Excel VBA代码的单元格中的某些文本周围插入方括号?
It needs to find the text before the first comma and if there are no square brackets before the first comma, wrap it with [ ] square brackets 它需要在第一个逗号之前找到文本,如果在第一个逗号之前没有方括号,请用[]方括号将其括起来
The text in cell A is in this format. 单元格A中的文本是这种格式。 It is all in one single text string
全部在一个文本字符串中
A12345, blah, blah, blah, blah blah
[B45678], blah, blah, blah, blah blah
C97665, blah, blah, blah, blah blah
D89798, blah, blah, blah, blah blah
[B97494], blah, blah, blah, blah blah
Y34987, blah, blah, blah, blah blah
I need to run it into 我需要运行它
[A12345], blah, blah, blah, blah blah
[B45678], blah, blah, blah, blah blah
[C97665], blah, blah, blah, blah blah
[D89798], blah, blah, blah, blah blah
[B97494], blah, blah, blah, blah blah
[Y34987], blah, blah, blah, blah blah
I have no VBA knowledge but thought it would be best handled using VBA as there could be thousands of rows 我没有VBA知识,但认为最好使用VBA进行处理,因为可能会有成千上万的行
With data like: 使用以下数据:
Running this small macro: 运行这个小宏:
Sub bracket()
Dim r As Range, N As Long, s As String
Dim i As Long
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
ary = Split(Cells(i, 1).Text, ",")
If Left(ary(0), 1) = "[" Then
Else
ary(0) = "[" & ary(0) & "]"
Cells(i, 1).Value = Join(ary, ",")
End If
Next i
End Sub
will produce: 将产生:
EDIT#1: 编辑#1:
To adapt the original code to work with data in column E we need to change 3 lines of code: 为了使原始代码适合E列中的数据,我们需要更改3行代码:
Sub bracket()
Dim r As Range, N As Long, s As String
Dim i As Long
N = Cells(Rows.Count, "E").End(xlUp).Row
For i = 1 To N
ary = Split(Cells(i, 5).Text, ",")
If Left(ary(0), 1) = "[" Then
Else
ary(0) = "[" & ary(0) & "]"
Cells(i, 5).Value = Join(ary, ",")
End If
Next i
End Sub
this is because Cells(13,1)
refers to cell A13 , and Cells(13,5)
would refer to cell E13 . 这是因为
Cells(13,1)
引用了单元格A13 ,而Cells(13,5)
引用了单元格E13 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.