Vba 区分两种不同类型的字符串并提取它们
因此,我在excel中有一列注释,这些注释类似于01/16 14:38 ATND[经销商/分销商的注释]JR和01/16 14:14 ATND[公司的注释]JR2和01/16 14:14 ATND[公司的注释]TLO该商品已延期订购 正如你在括号符号后看到的,有两个字母或三个字母的代码,分别是JR、JR2和TLO。我编写了一个程序,只区分JR和TLO,但如果代码编号为JR和JR2,则不会提取代码。如果有人能帮我,我将不胜感激Vba 区分两种不同类型的字符串并提取它们,vba,excel,Vba,Excel,因此,我在excel中有一列注释,这些注释类似于01/16 14:38 ATND[经销商/分销商的注释]JR和01/16 14:14 ATND[公司的注释]JR2和01/16 14:14 ATND[公司的注释]TLO该商品已延期订购 正如你在括号符号后看到的,有两个字母或三个字母的代码,分别是JR、JR2和TLO。我编写了一个程序,只区分JR和TLO,但如果代码编号为JR和JR2,则不会提取代码。如果有人能帮我,我将不胜感激 Sub G_ExtractCodes() Dim LR As Lon
Sub G_ExtractCodes()
Dim LR As Long
LR = Range("A" & Rows.Count).End(xlUp).Row
Dim i As Long
Dim NoteCodes As Range
For i = LR To 2 Step -1
Set NoteCodes = Range("O" & i)
If InStr(NoteCodes, "JR") >= 1 Then
Cells(i, 20) = "JR"
ElseIf InStr(NoteCodes, "JR2") >= 1 Then
Cells(i, 20) = "JR2"
ElseIf InStr(NoteCodes, "TLO") >= 1 Then
Cells(i, 20) = "TLO"
End If
Next i
End Sub
If语句中的第一个条件比第一个ElseIf子句更具限制性,因此JR2的任何实例都将被第一个测试捕获,只找到JR,而不计算ElseIf 改变你的逻辑,我认为这应该可以解决它:
If InStr(NoteCodes, "JR2") >= 1 Then
Cells(i, 20) = "JR2"
ElseIf InStr(NoteCodes, "JR") >= 1 Then
Cells(i, 20) = "JR"
ElseIf InStr(NoteCodes, "TLO") >= 1 Then
Cells(i, 20) = "TLO"
End If
或者,您可以解析代码,如:
Dim codeValue as String
Dim bracketLocation as Integer
For i = LR To 2 Step -1
Set NoteCodes = Range("O" & i)
'finds the position of the right bracket
bracketLocation = Instr(NoteCodes, "]")
'Lops off any characters up to & including the right square bracket
codeValue = Trim(Mid(NoteCodes, bracketLocation + 1))
'removes any text that appears *after* the code value, if any
If Instr(codeValue, " ") > 0 Then
codeValue = Left(codeValue, Instr(codeValue, " "))
End If
Cells(i, 20).Value = codeValue
'clear out the variable
codeValue = vbNullString
Next
代码是否总是紧跟在右方括号之后?大卫,是的。它们总是出现在方括号之后,也有一些没有代码的,在这种情况下,我希望这一行可以看到下面我的建议。干杯。我删除了你提到的图片的链接,因为链接已经死了。。。你的照片不可用谢谢@Jeeped,修好了@Robert,这不是吗?此脚本应仅为每个单元格提取一个codevalue;括号后立即出现的内容,仅此而已。David,我尝试过这个,但出于某些原因,它实际上没有任何作用。请修改您的Q,以显示您当前正在尝试实现的内容。David,你认为它没有循环通过的原因是因为代码中没有i来表示它要检查O列中的每一行吗?只是一个想法,但我可能错了。它给我一个错误,说变量未定义。该行高亮显示sn=Cells1.CurrentRegion.Columns1.Offset,15注释掉或删除“Option Explicit”,这样您就不会再被骚扰了。
Sub G_ExtractCodes()
sn=cells(1).currentregion.columns(1).offset(,15)
for j=1 to ubound(sn)
If InStr(sn(j,1), "JR") Then
Cells(j, 20) = iif(instr(sn(j,1),"JR2"),"JR2","JR")
ElseIf InStr(sn(j,1), "TL") Then
Cells(j, 20) = iif(instr(sn(j,1),"TL0"),"TL0","TL")
End If
Next
End Sub