如何優化這些函數?他們工作,但我需要它快得多。如何優化一組分析字符串和變體類型的VBA函數
實際工作(慢):
Function IsInArray(value As String, arr As Variant) As Boolean
Dim length As Integer
Dim found As Boolean
length = UBound(arr)
found = False
i = 0
While Not found And i < length
If arr(i) = value Then
found = True
End If
i = i + 1
Wend
If found Then
IsInArray = True
Else
IsInArray = False
End If
End Function
這得到特定列表的行數:
Function GetNumberOfRows(list As String) As Integer
Dim numRows As Integer
Dim row As Integer
Dim column As Integer
row = 2
column = 2
numRows = 0
While (Worksheets(list).Cells(row, column).value <> "")
numRows = numRows + 1
row = row + 1
Wend
GetNumberOfRows = numRows
End Function
這取代了一系列
Sub ReplaceValue(oldValue As String, newValue As String, list As String)
Dim numRows, numColumns As Integer
Dim row, column As Integer
numRows = GetNumberOfRows(list)
numColumns = 9
row = 2
While row <= numRows + 1
column = 3
While column <= numColumns + 3
If Worksheets(list).Cells(row, column).value = oldValue Then
Worksheets(list).Cells(row, column).value = newValue
End If
column = column + 1
Wend
row = row + 1
Wend
End Sub
P.S.值
這很快,但不是說我好像在搜索「aa」,如果「aab」在數組中,它會說TRUE。不過,將它作爲「快速」的例子包含在這裏可能是有益的。
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function