vba从领域使用instr和左/右拉名字

我再次大家。 我试图拉各种string,并将一个string放在一个单独的字段。 我似乎无法让我的代码工作,我希望有人可以照亮我有缺陷的尝试。 非常感谢你。

我有列“B”,其中包括多个名称,并在以下格式:

BCD Other Team teamOne teamTwo /jdoe/smithjr/ /someguy/testuser/ /obiwan/luke/darth /vader/ /hp/dell/lenova/mint/ 

我只需要把前两个名字放在一个字段中,一个名字放在另一个字段中。

预期成绩

  BCD Other Team teamOne teamTwo /jdoe/smithjr/ jdoe smithjr /someguy/testuser/ someguy testuser /obiwan/luke/darth obiwan luke /vader/ vader /hp/dell/lenova/mint/ hp dell 

我到目前为止的代码是在下面,不起作用。 我收到没有数据要replace的错误。

 For Q = 2 To 10 If UCase(Cells(Q, "B").Value) Like "*Other Team*" Then Name = Cells(Q, "B").Value startingPosition = InStr(Name, "/") Firstname = Left(Name, (startingPosition) - 1) secondName = Right(Name, startingPosition - 2) Cells(Q, "C").Value = Firstname Cells(Q, "D").Value = secondName End If Next Q 

我对VBA(第三天)很新,似乎无法弄清楚如何parsing这些数据。 也许有人可以解释我做错了什么,并帮助我? 谢谢。

既然你有一个分隔string,我个人使用Splitfunction。 注意你的If UCase(Cells(Q, "B").Value) Like "*Other Team*" Thentesting在你的样本数据中的每个input都失败 – 假设这是只对你跳过的列标题您可以像testinginput一样将testing更改为大写。 如果您正在尝试确定您是否在正确的工作表上,则需要跳出循环。

像这样的东西:

 If UCase$(Cells(1, "B").Value) Like "*OTHER TEAM*" Then Dim tokens() As String For Q = 2 To 10 Name = Cells(Q, "B").Value tokens = Split(Name, "/") If UBound(tokens) > 0 Then Cells(Q, "C").Value = tokens(1) If UBound(tokens) > 1 Then Cells(Q, "D").Value = tokens(2) Next Q End If 

只是为了提出一个“公式”的方法

Sub main()

 If UCase$(Cells(1, "B").Value) Like "*OTHER TEAM*" Then Range("c2:c10").FormulaR1C1 = "=MID(RC2,2,SEARCH(""/"",RC2,2)-2)" Range("d2:d10").FormulaR1C1 = "=IF(ISNUMBER(SEARCH(""/"",RC2,SEARCH(""/"",RC2,2)+1)),MID(RC2,SEARCH(""/"",RC2,2)+1,SEARCH(""/"",RC2,SEARCH(""/"",RC2,2)+1)-SEARCH(""/"",RC2,2)-1),"""")" End If 

一个更“清晰”的格式可能是

 Dim str1 As String, str2 As String, formula1 As String, formula2 As String str1 = "SEARCH(""/"",RC2,2)" str2 = "SEARCH(""/"",RC2," & str1 & "+1)" formula1 = "=MID(RC2,2," & str1 & "-2)" formula2 = "=IF(ISNUMBER(" & str2 & "),MID(RC2," & str1 & "+1," & str2 & "-" & str1 & "-1),"""")" If UCase$(Cells(1, "B").Value) Like "*OTHER TEAM*" Then Range("c2:c10").FormulaR1C1 = formula1 Range("d2:d10").FormulaR1C1 = formula2 End If