【问题标题】:vba pulling names from fields using instr and left/rightvba 使用 instr 和左/右从字段中提取名称
【发布时间】:2016-03-31 17:26:51
【问题描述】:

大家又是我。我正在尝试拉各种字符串并将字符串放在单独的字段中。我似乎无法让我的代码工作,我希望有人能在我有缺陷的尝试中有所启发。非常感谢。

我的“B”列包含多个名称,格式如下:

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

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

预期结果

       B                    C         D
   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

到目前为止我想出的代码如下,但不起作用。我收到没有数据可替换的错误。

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 很陌生(第 3 天),似乎无法弄清楚如何解析这些数据。也许有人可以解释我做错了什么并帮助我?谢谢。

【问题讨论】:

  • 如果Cells(Q, "C").Value = FirstnameCells(Q, "D").Value = secondName 命令在“C”和“D”中留下“/”字符,那很好,因为我计划从“C”行中删除所有这些字符然后是“D”。
  • 嗯,我会在开车回家的路上思考这个问题,然后在家里继续这个问题。
  • 提示 2:instr 接受 3 个参数。
  • 第一天使用instr。 VBA 有相当长的学习曲线(至少对我而言)哈哈。
  • 忘记 Instr 并使用 Split function

标签: vba excel


【解决方案1】:

由于您有一个分隔字符串,我个人会使用Split 函数。另请注意,您的 If UCase(Cells(Q, "B").Value) Like "*Other Team*" Then 测试在您的示例数据中的每个输入上都失败 - 它仅适用于您跳过的列标题,假设您像输入一样将测试更改为大写。如果您试图确定您是否在正确的工作表上,它需要跳出循环。

类似这样的:

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

【讨论】:

  • 这绝对完美。非常感谢!
  • “其他团队”只是一个错字,不是全部大写。
【解决方案2】:

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

子主()

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

【讨论】:

    猜你喜欢
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多