2012-12-13 91 views
2

我有這樣的代碼:VB6聲明數組

' 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 ???????)?

+0

@george:感謝編輯,它看​​起來好多了...... – faid

回答

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,也沒有在聲明變量的初始化語法。

+0

哇,感謝您的建議哥們,我必須嘗試這一切,它看起來更好... – faid

+0

爲了好奇,我跑了不同版本再加上一個我用正則表達式寫的。我使用這個測試字符串測試了它:「nc834u \ 7238/4037 *?」。 第一個版本花了30秒運行100,000次。 第二個和第三個版本每個都花費23秒來運行1,000,000次。 正則表達式需要17秒到100萬次。適度增加。 我應該注意到,只有編譯並運行時,增加纔是明顯的。在解釋模式下運行時,它與版本2和3的運行時間相同。如果有人想要,我會在單獨的註釋中發佈我的代碼。 –

+0

'Function Clean1(S As String)As String Dim regex As New RegExp regex.Pattern =「[\\ /:\?\ * \」「\ <\> \ |]」 正則表達式。IgnoreCase = True regex.Global = True Clean1 = regex.Replace(S,「」) End Function' 注意:您必須添加對Microsoft VBScript Regular Expressions **的引用才能使其正常工作。 –

0

數組聲明方式與其他變量(即使用關鍵字「Dim」,「Private」,「Public」等)的聲明方式相同,只是數組邊界使用變量名後面的括號編碼(if一個固定長度的數組正在被聲明),或者一對空括號用於變量名稱(如果聲明瞭可變長度或動態數組)。

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

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

+0

你的代碼實際上**不起作用**,但感謝您的鏈接,現在我宣佈它爲'Variant' – faid

+0

而不是說它不起作用可以提供錯誤消息? –

+0

這是錯誤的,當我鍵入它,因爲我的vb6不能在DIM之後有一個* equal * Dim'無論作爲無論=無論',所以錯誤沒有顯示任何東西,它只是突出顯示'='符號... – faid

1

你可以調暗它作爲一個字符串數組 你不會需要一個變種這樣做

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