简体   繁体   English

将 Excel 数组公式转换为 VBA 代码

[英]Convert Excel Array formula into VBA code

I have two set of range named as LIST_KEY and LIST_CAT .我有两组名为LIST_KEYLIST_CAT的范围。 In Column A, user will add some data which will contain one of the one of the text from LIST_KEY .在 A 列中,用户将添加一些数据,这些数据将包含LIST_KEY中的文本之一。 I would like to get corresponding Category list from LIST_CAT depends upon the Key value我想从LIST_CAT获取相应的类别列表取决于键值

在此处输入图像描述

I am using below VBA code to achieve this.我正在使用下面的 VBA 代码来实现这一点。 This include a Array formula.这包括一个数组公式。

Sub match()

Dim ss As Workbook

Dim test As Worksheet

Set ss = Excel.Workbooks("test.xlsm")
Set test = ss.Worksheets("Sheet1")

For i = 2 To test.Cells(Rows.Count, "A").End(xlUp).Row

Cells(i, "B").FormulaArray = "=INDEX(LIST_CAT,MATCH(TRUE,ISNUMBER(SEARCH(LIST_KEY,RC[-1])),0))"

Cells(i, "B").Formula = Cells(i, "B").Value

Next i

End Sub

This code works perfect if there is less data to fetch.如果要获取的数据较少,则此代码可以完美运行。 But in my original use case, I will have around 8000 rows.但在我最初的用例中,我将有大约 8000 行。 Due to this large number of columns excel will go to not responding state after 2-3 minutes.由于有大量列 excel 将 go 在 2-3 分钟后没有响应 state。

Instead of adding Array formula to column B, Is there anyway to convert that into VBA to run this faster.不是将数组公式添加到 B 列,而是将其转换为 VBA 以更快地运行。 Sorry, I am new to this VBA stuff and dont have much experience抱歉,我是 VBA 的新手,没有太多经验

Try the following code, which uses arrays instead of worksheet formulas...试试下面的代码,它使用 arrays 而不是工作表公式...

Option Explicit

Sub GetCategories()

    Dim sourceWorkbook As Workbook
    Set sourceWorkbook = Workbooks("test.xlsm")

    Dim sourceWorksheet As Worksheet
    Set sourceWorksheet = sourceWorkbook.Worksheets("Sheet1")

    Dim lookupArray As Variant
    lookupArray = sourceWorkbook.Names("LIST_KEY").RefersToRange.Value

    Dim returnArray As Variant
    returnArray = sourceWorkbook.Names("LIST_CAT").RefersToRange.Value

    Dim tableArray As Variant
    Dim lastRow As Long
    With sourceWorksheet
        lastRow = .Cells(.Rows.Count, "a").End(xlUp).Row
        tableArray = .Range("A2:B" & lastRow).Value
    End With

    Dim desc As String
    Dim i As Long
    Dim j As Long
    For i = LBound(tableArray, 1) To UBound(tableArray, 1)
        desc = tableArray(i, 1)
        For j = LBound(lookupArray, 1) To UBound(lookupArray, 1)
            If InStr(1, desc, lookupArray(j, 1), vbTextCompare) > 0 Then
                tableArray(i, 2) = returnArray(j, 1)
                Exit For
            End If
        Next j
    Next i

    sourceWorksheet.Range("B2").Resize(UBound(tableArray, 1), 1).Value = Application.Index(tableArray, 0, 2)

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM