【问题标题】:VBA Function Return string type mismatch errorVBA函数返回字符串类型不匹配错误
【发布时间】:2017-03-24 11:53:55
【问题描述】:

我正在用 VBA 为 Excel 2010 编写一个宏。我觉得我的理解中缺少一些基本的东西。我已经填充了一个字符串数组并迭代了该数组中的内容。数组中的文本来自一个 html 格式的电子邮件,并且有很多不间断的空格。我想删除这些和其他非打印字符,以便我的输出只包含文本。

    For Each str In stringArr()
        CleanString (str)
        If Len(str) <> 0 Then
            Cells(Row + 1, 6 + index) = str
            index = index + 1
        End If            
    Next str

CleanString() 返回一个字符串作为返回类型,但 str 不会改变。我试过了:

testString = cleanString(str)

给出类型不匹配错误。有什么建议吗?

更多信息...

Function cleanString(sInput As String) As String
    Dim sResult As String
    sResult = sInput
    sResult = Replace(sResult, Chr(10), "")
    sResult = Replace(sResult, Chr(13), "")
    sResult = Replace(sResult, Chr(9), "")
    sResult = Replace(sResult, ChrW(160), "")
    sResult = Replace(sResult, Chr(32), "")
    Trim$ (sResult)
    Application.WorksheetFunction.Clean (sInput)
    cleanString = sResult
    Exit Function

End Function

【问题讨论】:

  • 你能说明CleanString的定义吗?
  • 用更多信息编辑了问题。
  • 数组可能没有字符串格式。如果您将 cleanString 的参数指定为 ByVal sInput As String,VBA 会将字符串类型数组强制转换为字符串。 CleanString(str) 传递参数 ByVal,这意味着您必须将返回值分配给调用过程中的变量,例如 str = cleanString(str),但您必须已将 str 声明为 String。在结束函数之前不需要退出函数。
  • 感谢 Variatus。您已经指出问题出在哪里......要用于每个,str 需要是 var,但我想用字符串做一些事情。越来越近了。

标签: string vba excel


【解决方案1】:

感谢您的帮助。 问题在于指定 cleanString() 需要一个字符串。 将其更改为 cleanString(as Variant),意味着我可以:

str = cleanString(str)

感谢 Variatus

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多