2

我有这个代码:

' Option Explicit
Public Function Clean(Text)
    On Error Resume Next
    ' Dim Chars As ?????????
    Chars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
    For Each Replaced In Chars
        Text = Replace(Text, Replaced, "")
    Next
    Clean = CStr(Text)
End Function

但是我在使用时出现错误,Option Explicit因为没有声明 Chars,但是我必须使用什么类型来使数组变暗(Dim Chars As ???????)?

4

3 回答 3

6

修正版:

Option Explicit

Public Function Clean(ByVal Text As String)
    Dim Chars As Variant
    Dim Replaced As Variant

    Chars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
    For Each Replaced In Chars
        Text = Replace(Text, Replaced, "")
    Next
    Clean = Text
End Function

通常性能更好的版本:

Option Explicit

Public Function Clean(ByVal Text As String)
    Dim Chars As Variant
    Dim RepIndex As Long

    Chars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
    For RepIndex = 0 To UBound(Chars)
        Text = Replace$(Text, Chars(RepIndex), "")
    Next
    Clean = Text
End Function

理解变体很重要,应该特别注意使用字符串函数的变体版本,而不是使用“$”类型修饰后缀的字符串类型版本。

大多数时候,由于性能成本,您会希望尽可能避免使用变体。

这个版本可能表现得更好:

Option Explicit

Public Function Clean(ByVal Text As String)
    Const Chars As String = "\/:*?""<>|"
    Dim RepIndex As Long

    For RepIndex = 1 To Len(Chars)
        Text = Replace$(Text, Mid$(Chars, RepIndex, 1), "")
    Next
    Clean = Text
End Function

VB6 中没有“Char”类型,变量声明也没有任何初始化语法。

于 2012-12-13T13:23:10.623 回答
2

您可以将其调暗为字符串数组,您不需要变体即可

Dim Chars() As String
Chars = Split("\,/,:,*,?,"",<,>,|", ",")
于 2012-12-19T11:15:48.193 回答
1

数组以与其他变量相同的方式声明(即使用关键字“Dim”、“Private”、“Public”等),除了数组边界在变量名后面的括号中编码(如果是固定长度数组被声明)或一对空括号跟随变量名(如果正在声明可变长度或动态数组)。

 Dim Chars As Variant
 Chars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")

http://www.vb6.us/tutorials/understanding-arrays

于 2012-12-13T13:05:57.473 回答