我有这段代码:
' 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 ???????
)?
答案 0 :(得分: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
理解变体很重要,应该特别注意使用Variant版本的字符串函数而不是带有“$”类型装饰后缀的String类型。
大多数情况下,由于性能成本,您可能希望尽可能避免使用Variants。
这个版本的表现可能更好:
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”类型,变量声明也没有任何初始化语法。
答案 1 :(得分:2)
你可以把它变成一个字符串数组 你不需要一个变体来这样做
Dim Chars() As String
Chars = Split("\,/,:,*,?,"",<,>,|", ",")
答案 2 :(得分:1)
以与其他变量相同的方式声明数组(即使用关键字“Dim”,“Private”,“Public”等),除了数组边界在变量名后面的括号中编码(如果是正在声明固定长度数组)或一对空括号跟随变量名称(如果声明了可变长度或动态数组)。
Dim Chars As Variant
Chars = Array("\", "/", ":", "*", "?", """", "<", ">", "|")