vba 查找值,然后将另一个值粘贴到另一列的不同单元格中

标签 vba excel

我目前正在运行一个宏,它从工作表 2 的 C 列中的“工作表 1”的 A 列中查找值,如果这些匹配,则应将工作表 1 的 B 列中的值复制到工作表 2 中的相应行。

我的宏有效,但由于这是一个庞大的工作表,其中的循环花费了太多时间。这是因为工作表 1 有大约 300,000 行,并且每个实例中的值都是唯一的。在工作表 2 中,大约有 50,000 行。它已经运行了一夜,到目前为止在工作表 1 中只达到了 60,000 行

我绝不是 VBA 专家,甚至不是中级专家,但根据我的阅读,使用 Find 可能比查找匹配项和循环更快?

这是我目前正在使用的宏

 Option Explicit

Sub lookupandcopy()
Application.Screenupdating = True

Dim j As Long, i As Long, lastRow1 As Long, lastRow2 As Long
Dim sh_1, sh_3 As Worksheet
Dim MyName As String

Set sh_1 = Sheets("sheet1") 
Set sh_3 = Sheets("sheet2")


lastRow1 = sh_1.UsedRange.Rows.Count 

For j = 2 To lastRow1
MyName = sh_1.Cells(j, 1).Value 


lastRow2 = sh_3.UsedRange.Rows.Count

For i = 2 To lastRow2
    If sh_3.Cells(i, 3).Value = MyName Then
        sh_3.Cells(i, 13).Value = sh_1.Cells(j, 2).Value 
    End If

    Next i

  Next j

Application.Screenupdating = True
End Sub

如果我遗漏了任何内容或任何其他需要的细节,请告诉我!

最佳答案

您似乎将 sheet1 中的 A 列和 B 列用作字典(并通过线性搜索访问这些值)。为什么不将值加载到具有 O(1) 搜索的字典对象中?确保您的项目包含对 Microsoft Scripting Runtime 的引用(工具 > VBE 中的引用,如果您还没有这样做的话)然后尝试:

Sub lookupandcopy()
    Application.ScreenUpdating = False

    Dim AVals As New Dictionary
    Dim i As Long, j As Long, lastRow1 As Long, lastRow2 As Long
    Dim sh_1, sh_3 As Worksheet
    Dim MyName As String

    Set sh_1 = Sheets("sheet1")
    Set sh_3 = Sheets("sheet2")

    With sh_1
        lastRow1 = .Range("A:A").Rows.Count 'last row in spreadsheet
        lastRow1 = .Cells(lastRow1, 1).End(xlUp).Row 'last used row in column A
        'load the AVal dict
        For j = 2 To lastRow1
            MyName = .Cells(j, 1).Value
            If Len(MyName) > 0 Then AVals.Add MyName, .Cells(j, 2).Value
        Next j
    End With

    With sh_3
        lastRow2 = .Range("A:A").Rows.Count
        lastRow2 = .Cells(lastRow2, 3).End(xlUp).Row 'last used row in column 3
        For i = 2 To lastRow2
            MyName = .Cells(i, 3).Value
            If AVals.Exists(MyName) Then
                .Cells(i, 13).Value = AVals.Item(MyName)
            End If
         Next i
    End With
    Application.ScreenUpdating = True
End Sub

如果你在 A 列中有重复的值,那么你需要做一些事情,比如存储值出现的行索引的值集合,但设置这样一个字典的工作仍然比使用嵌套循环更好。

关于vba 查找值,然后将另一个值粘贴到另一列的不同单元格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31071004/

相关文章:

excel - 防止 VBA 选择不同的工作表

vba - 使用vba从单元格中删除图片

vba - 返回 Excel 图表使用 VBA 引用的工作表

android - Android Excel CSV 的哪种 MIME 数据类型?

arrays - 数组 CountIf 替换 - Count(Match())

javascript - VBA 抓取 JavaScript 生成的内容

html - 使用 VBA 以 HTML 形式通过 <input\input> 上传文件

excel - 如何搜索文本中的字符列表

vba - 列表框在 Excel VBA 中无法正确返回数据

excel - 为什么第一个随机数总是一样的?