我已经在vba中编写了一个脚本来有条件地操纵某些单元格的内容。但是,我很难解决这个问题。我在下面尝试的方法是一种错误的方法,但这是我所能做的最好的事情。
条件:如果某个单元格包含
{
,后跟any nummber
,再次包含+
,则应按原样放置它。否则,应从该内容中踢出{
和}
符号,并将其放置在其相邻列中。
内容在Range("A1:A4")
中。精炼后的内容应放在相应单元格的相邻列中。
我尝试过:
Sub GetRefinedContent()
Dim cel As Range
For Each cel In Range("A1:A4")
If Left(cel, 3) = "{" Then ' a faulty approach definitely
cel(1, 2) = Replace(Replace(cel, "{", ""), "}", "")
End If
Next cel
End Sub
上面的宏没有做任何事情,因为从不满足条件。
内容是:
a^{5}b^{7}
a^{5+x}b^{7+y}
a^{3}b^{5}
a^{3+x}b^{5+y}
预期输出:
a^5b^7
a^{5+x}b^{7+y}
a^3b^5
a^{3+x}b^{5+y}
答案 0 :(得分:1)
使用正则表达式
Option Explicit
Public Sub test()
Application.ScreenUpdating = False
Dim loopRange As Range, rng As Range, ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ws
Set loopRange = .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).Row)
End With
For Each rng In loopRange
rng.Offset(, 1) = GetString(rng.Value)
Next rng
Application.ScreenUpdating = True
End Sub
Public Function GetString(ByVal inputString As String) As String
Dim regex As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = "\{\d\+"
End With
If Not regex.test(inputString) Then
GetString = Replace(Replace$(inputString, "{", vbNullString), "}", vbNullString)
Else
GetString = inputString
End If
End Function
答案 1 :(得分:0)
尝试一下。它应该解决问题。查看this link,了解有关Like
运算符的信息。
Sub GetRightPart()
Dim cel As Range
For Each cel In Range("A1:A4")
If Not cel Like "*{?+*" Then
cel(1, 2) = Replace(Replace(cel, "{", ""), "}", "")
Else:
cel(1, 2) = cel
End If
Next cel
End Sub