我想从单元格中获取单词。例如,单元格A2的值为“我的名字是jayson”。我想得到的话是:“名字”& “杰森”。我想要排除少于3个字符的单词。如何使用excel中的公式/函数来完成?
感谢。
答案 0 :(得分:3)
此代码应从包含要拼接的数据的工作表运行。我假设您正在A列中工作
代码
变体数组用于使其成为一个有效的过程
{更新:未添加循环版本}
<强> Original Code
强>
Sub Spliced()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim rng1 As Range
Dim objRegex
Dim X
Dim lngRow As Long
Set ws1 = Sheets(1)
Set rng1 = ws1.Range(ws1.[a1], ws1.Cells(Rows.Count, "A").End(xlUp))
Set ws2 = Sheets.Add
X = rng1.Value2
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "\b\w{1,3}\b"
.Global = True
End With
For lngRow = 1 To UBound(X)
X(lngRow, 1) = Application.Trim(objRegex.Replace(X(lngRow, 1), vbNullString))
Next
ws2.Range(rng1.Address) = X
ws2.Columns("A").TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Space:=True
End Sub
Updated:No loops
Sub Spliced_NoLoops()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim rng1 As Range
Dim objRegex
Dim strDelim As String
Dim strOut As String
strDelim = "||"
Set ws1 = Sheets(1)
Set rng1 = ws1.Range(ws1.[a1], ws1.Cells(Rows.Count, "A").End(xlUp))
strOut = Join(Application.Transpose(rng1), strDelim)
Set ws2 = Sheets.Add
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "\b\w{1,3}\b"
.Global = True
End With
ws2.Range(rng1.Address) = Application.Transpose(Split(Application.Trim(objRegex.Replace(strOut, vbNullString)), "||"))
ws2.Columns("A").TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Space:=True
End Sub
答案 1 :(得分:2)
你没有表现出你曾经尝试过的东西,所以从头开始编码...
将单元格到分割的范围传递给此函数,该函数大致如下:
请在运行任何VBA之前始终保存您的工作。干杯,快乐的编码。
function splitter(byref rng as range)
dim return_value as collection
set return_value = new collection
dim split_result as variant
dim idx as integer
split_result = split(rng.value, " ")
for idx = lbound(split_result) to ubound(split_result)
if len(split_result(idx)) > 2 then
return_value.add(split_result(idx))
end if
next
splitter = return_value
end function
我手边没有Windows或Mac OS进行测试,但语法应该是正确的,如果不是这样的话。