我有这样的代码:
' 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时得到了一个错误,因为字符没有声明,但是我必须使用什么类型来暗显一个数组(Dim Chars As ???????)?
发布于 2012-12-13 21:23:11
更正后的版本:
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 FunctionVB6中没有Char类型,变量声明上也没有初始化语法。
发布于 2012-12-19 19:15:48
您可以将其转换为字符串数组,这样做不需要变量
Dim Chars() As String
Chars = Split("\,/,:,*,?,"",<,>,|", ",")发布于 2012-12-13 21:05:57
数组的声明方式与其他变量相同(即使用关键字"Dim“、"Private”、"Public“等),不同之处在于数组边界在变量名后面的圆括号中编码(如果声明的是固定长度数组),或者变量名后面的一对空括号(如果声明的是可变长度数组或动态数组)。
Dim Chars As Variant
Chars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")http://www.vb6.us/tutorials/understanding-arrays
https://stackoverflow.com/questions/13860458
复制相似问题