【问题标题】:Taking last word of an string, variable not declared?取字符串的最后一个单词,变量未声明?
【发布时间】:2017-04-07 17:49:55
【问题描述】:

我正在获取一个单元格值(有时是“flores”,有时是“de las flores”),但我无法真正知道该值,因为有 10000 多条记录。

我想做的就是只取“flores”(最后一个词,如果只有一个,那么,那个)。我试过使用 split 然后 ubound,但我得到一个“未声明”的错误。但我试图让它隐含。

Function CheckFirstLetter(mystring, text, indexCurp, index) As Boolean
            Dim outStr, asciinum, vocal As String, i As Long
---->            arr = Split(mystring, " ")
---->            vocal = arr(UBound(ary))
            outStr = LCase(Mid(text, indexCurp, 1))
            asciinum = LCase(Mid(mystring, 1, 1))
            Cells(index, "M") = vocal
            Cells(index, "O") = asciinum
            If (asciinum = outStr) Then
                CheckFirstLetter = True
                Else: CheckFirstLetter = False
                End If
End Function

谢谢!

【问题讨论】:

  • 请您改写您的问题?至少对我来说还不清楚?
  • 感谢使用Option Explicit 告诉您拼写错误。下一步,修正错别字。 ary 不是 arrarr 声明在哪里?

标签: arrays vba excel split


【解决方案1】:

我相信无论如何你都过于复杂了。除非我读错了(很有可能),否则你可以简化很多。

Function CheckFirstLetter(mystring, text, indexCurp, index) As Boolean
    Dim vocal() As String

    vocal = Split(mystring, " ")

    Cells(index, "M") = vocal(UBound(vocal))
    Cells(index, "O") = LCase(Mid(mystring, 1, 1))

    CheckFirstLetter = Cells(index, "O") = LCase(Mid(text, indexCurp, 1))

End Function

【讨论】:

    【解决方案2】:

    “变量未声明”是一个编译时错误,表示您指定了Option Explicit - 这是一个优秀的事情,不要删除它!

    但我试图让它隐含。

    没有理由想要这样做。

    Option Explicit 需要变量声明。所以你必须声明你使用的所有变量。

    如果您想要一个变量的隐式 type,请在没有 As 子句的情况下声明它:

    Dim arr ' implicit: As Variant
    

    我怀疑ary 是这里的错字:

    vocal = arr(UBound(ary))
    

    如果这是为了让项目位于arr 的上限,那么ary 应该是arr


    这是多余的:

    If (asciinum = outStr) Then
        CheckFirstLetter = True
        Else: CheckFirstLetter = False
        End If
    

    可以写成一个简单的作业:

    CheckFirstLetter = (asciinum = outStr)
    

    您的代码已经非常隐含。这两条指令隐含引用了ActiveSheet

    Cells(index, "M") = vocal
    Cells(index, "O") = asciinum
    

    这些声明将outStrasciinum 声明为隐式Variant

    Dim outStr [As String], asciinum [As String], vocal As String, i As Long
    

    所有参数都隐式传递ByRefByVal 就足够了),它们也都是隐式Variant

    mystring, text, indexCurp, index
    

    VS

    ByVal mystring As String, ByVal text As String, ByVal indexCurp As Long, ByVal index As Long
    

    这些函数调用返回一个Variant,这意味着如果outStrasciinum是字符串,则隐式转换为String

    outStr = LCase(Mid(text, indexCurp, 1))
    asciinum = LCase(Mid(mystring, 1, 1))
    

    这些将返回String

    outStr = LCase$(Mid$(text, indexCurp, 1))
    asciinum = LCase$(Mid$(mystring, 1, 1))
    

    看,你的代码已经有足够的隐含性了。除此之外,不需要隐式变量!感谢:

    • 使用显式选项
    • 返回显式Boolean
    • 使用PascalCase 命名您的函数

    【讨论】:

      猜你喜欢
      • 2013-09-07
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      相关资源
      最近更新 更多