vba - 如何优化一组解析字符串和变体类型的 VBA 函数

标签 vba excel

如何优化这些功能?他们工作,但我需要它更快。

实际工作(慢):

  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

附言

这很快,但并不像我正在搜索“aa”那样指定,如果“aab”在数组中,它会说 TRUE。然而,在这里将它作为“快速”的示例包含在内可能是有益的。
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean 
    IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

最佳答案

关于 IsInArray , 过滤器 不行,但是加入工作得很好。这假设重音符号不在数组中(不是一个严重的问题!):

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    jn = "`" & Join(arr, "`") & "`"
    IsInArray = InStr(1, jn, "`" & stringToBeFound & "`") > 0
End Function

关于vba - 如何优化一组解析字符串和变体类型的 VBA 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20252316/

相关文章:

vba - 引用列号的求和函数 VBA

python - 从单元格中检索完整的富文本数据(单元格内有多种字体颜色/样式)

python - 使用 win32com 打开带有公式的 Excel 文件,添加一些延迟,然后另存为 CSV

excel - 使用 VBA 将带有数据的 Excel 图表粘贴到 PowerPoint 中

VBA 错误 "Bubble Up"

excel - VBA 代码 - 数据库自动筛选与另一个工作表中的单元格

excel - 如何使用数组作为范围?

vba - 如何在 VBA 中为类模块声明静态变量?

excel - 如何将 DB2 日期时间字符串转换为 Excel 日期

performance - VBA屏幕更新和效率