区分两种不同的字符串并提取它们

时间:2015-01-22 15:13:07

标签: vba excel-vba excel

所以我在Excel中有一列笔记,其中包含" 01/16 14:38 ATND [来自经销商/分销商的注释] JR "和#34; 01/16 14:14 ATND [公司注释] JR2 "和#34; 01/16 14:14 ATND [公司注释] TLO该项目已重新订购"

正如您在支架标志后看到的那样,有三个不同变体的两个字母或三个字母代码,JR,JR2和TLO。我编写了一个程序,只能区分JR和TLO,但如果编号为JR和JR2,则不会提取代码。如果有人可以帮助我,我会非常感激。

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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