简体   繁体   English

使用 VBA 在大型 Excel 表中搜索值的最佳方法是什么?

[英]What is the best way to search for a value in a large Excel sheet using VBA?

I am currently working on an excel Userform to generate a report for a lot entered on a given day.我目前正在使用 excel 用户表单来为给定日期输入的批次生成报告。 The report is stored in a separate word document which contains the results of between 1 and 8 quality samples (number of samples varies by lot).该报告存储在一个单独的 Word 文档中,其中包含 1 到 8 个质量样本的结果(样本数量因批次而异)。 The Userform is meant to load in excel, receive a lot number and date from the user, retrieve samples from that day and lot from a different sheet in the excel workbook and then copy the data into a new word doc based on a custom template.用户表单旨在加载 excel,从用户那里接收批号和日期,从 excel 工作簿中的不同工作表中检索当天的样品和批次,然后将数据复制到基于自定义模板的新 word 文档中。 I have inserted the MsgBox method into the macro at various points for bug-squashing purposes.为了消除错误,我已将 MsgBox 方法插入到宏的各个点。 The data set I am using is organized by both date and lot number (in columns A and C, respectively) and the goal of the macro I am writing is to copy all rows containing a chosen date and lot number into a word document.我使用的数据集按日期和批号组织(分别在 A 列和 C 列中),我编写的宏的目标是将包含所选日期和批号的所有行复制到 Word 文档中。

I have encountered a problem where the Application.Match() function is not returning the correct response when I use it to search for a particular lot number.我遇到了一个问题,当我使用Application.Match() function 搜索特定批号时,它没有返回正确的响应。 I haven't yet found a better way to search for an exact data point in a data set, and I am also struggling to match the pDay to the date object stored in the spreadsheet.我还没有找到更好的方法来搜索数据集中的确切数据点,而且我还在努力将pDay与存储在电子表格中的日期 object 匹配。

Sub makeReport(lNum As Integer, pDay As Date, name As String)
    'Template Path: \\CORE\Miscellaneous\Quality\Sample Reports\Template\Defect Report.dotm
    'Save path for finished report: \\CORE\Miscellaneous\Quality\Sample Reports
    
    'Initialize word objects and open word
    Dim wApp As Word.Application
    Dim wDoc As Word.Document
    Dim wCell As Word.Cell
    
    MsgBox ("Word Doc Opened")
    
    Set wApp = New Word.Application
    wApp.Visible = True
    Set wDoc = wApp.Documents.Add(Template:=("\\CORE\Miscellaneous\Quality\Sample Reports\Template\Defect Report.dotm"), NewTemplate:=False, DocumentType:=0)
    
    MsgBox ("Word Objects Initialized")
    
    'Fill in lot number and date at top of report
    With wDoc
        .Application.Selection.Find.Text = "<<date>>"
        .Application.Selection.Find.Execute
        .Application.Selection = Format(pDay, "mm/dd/yyyy")
        .Application.Selection.EndOf
    
        .Application.Selection.Find.Text = "<<lot>>"
        .Application.Selection.Find.Execute
        .Application.Selection = lNum
    End With
    
    MsgBox ("Filled in pack date and lot number")
    
    'Initialize excel objects
    Dim wBook As Workbook
    Dim wFunc As WorksheetFunction
    
    Set wFunc = Application.WorksheetFunction
    Set wBook = ThisWorkbook
    
    Worksheets("Defect Table").Activate
    Application.ActiveSheet.UsedRange.Select
    
    MsgBox ("Set Active Sheet to Defect Table")
    
    'Initialize copy control variables
    Dim rowArray(7) As Integer
    Dim tBound As Integer
    Dim cRange As Range
    Dim vRange As Range
    Dim count As Integer
    Dim tHold As Variant
    Dim i As Long
    
    
    'Counter for do while loop
    count = 0
    
    'Range object containing all used cells
    Set cRange = ActiveSheet.UsedRange.Rows
    
    'First row containing desired lot number
    tHold = Application.Match(lNum, cRange, 0)
    tBound = CInt(tHold)
    
    MsgBox ("First found row: " + CStr(tBound))
    
    rowArray(0) = tBound
    
    'Range object containing all unscanned used cells
    Set vRange = cRange.Offset(tBound, 0)
    
    MsgBox ("Copy control variables initialized")
    
    'Finds and stores row numbers of desired samples
    Do While count < 7 And tBound < 3000
        'Adjusts vrange
        Set vRange = cRange.Offset(tBound, 0)
        i = CLng(count + 1)
        
        'Checks if row contains correct date, then copies row number into an array
        If (pDay = vRange.Cells(tBound, 1).Value()) Then
            rowArray(i) = tBound
            count = count + 1
        End If
        
        tBound = tBound + 1
    Loop
    
    count = 0
    
    'Prints out contents of rowArray
    Dim msg As String
    msg = "Row numbers of samples: "
    
    Do While count < 7
        msg = msg + vbCrLf + CStr(rowArray(count))
        count = count + 1
    Loop
    
    MsgBox (msg)
    
    count = 0
    
    MsgBox ("Appropriate samples found")
    
    'Copies samples over to word doc
    'Do While count < 7
    
    'Loop
    
    '---MsgBox ("Data copied to Word Doc")
    
    'Saves Document using regular name format for ease of access
    '---wDoc.SaveAs2 Filename:="\\CORE\Miscellaneous\Quality\Sample Reports\" + name, FileFormat:=wdFormatDocumentDefault, AddtoRecentFiles:=False
    
    'Zeroes out word/excel objects
    '---Set wDoc = Nothing
    '---Set wApp = Nothing
    '---Set wBook = Nothing
    
    '---MsgBox ("Report saved and objects zeroed out")
End Sub

First Occurrence by Rows (Find)按行首次出现(查找)

Using the Find method you can do the following:使用Find方法,您可以执行以下操作:

Dim cel As Range
Dim tBound As Long
Set cRange = ActiveSheet.UsedRange
Set cel = cRange.Find( _
    What:=lNum, _
    After:=cRange.Cells(cRange.Cells.CountLarge), _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows)
If cel Is Nothing Then
    MsgBox "'" & lNum & "' not found in range '" & cRange.Address & "'."
    Exit Sub
End If
' No need for 'tHold'.
' If `cRange` starts in the first row, the following results are equal.
tBound = cel.Row ' worksheet row
'tBound = cel.Row - cRange.Row + 1 ' range row
MsgBox "First found row: " & CStr(tBound)

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

相关问题 将大型Excel工作表加载到Informix表的最佳方法是什么? - What is the best way to load a large Excel sheet to an Informix table? 使用VBA在Excel中绘制的最佳方法是什么? - What is the best way to draw in Excel using VBA? 使用Excel VBA在工作表1中的名称范围内搜索文本并在工作表2中返回值 - Search for text in name range in Sheet 1and return Value in Sheet 2 using Excel VBA 在Excel中过滤大型列表的最佳方法是什么? - What is the best way to filter a large list in Excel? 将非常大的数组读入 Excel 表的最佳方法 - Best way to read a very large array into excel sheet 如何使用公式在Excel工作表中搜索值? - How to search for a value in the excel sheet using formula? Excel VBA-在sheet2中的sheet1中搜索值,并使用sheet1中的相邻值进行更新 - Excel VBA - Search for value from sheet1 in sheet2 and update with adjacent value from sheet1 使用 Talend Job 在 excel 中添加数据透视表的最佳方法是什么? - What is the best way to add a pivot table sheet in excel using Talend Job? 使用VBA Find What:=检索工作表中的值 - Using VBA Find What:= to retrieve a value in a sheet 文本挖掘-挖掘描述性Excel工作表数据的最佳方法是什么 - Text Mining - What is the best way to mine descriptive excel sheet data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM