繁体   English   中英

Excel VBA 从数组的单元格中查找值并将值返回到新列

[英]Excel VBA Find a value within a cell from an array and return value to new column

美好的一天,我是 VBA 的新手。我没有包含我尝试过的代码,因为没有什么比这更接近了。

我有一个大约 10,000 的数据范围,其中包含建筑物、部门、用户名和可能的其他信息。 此信息在 B 列中。名称不在每个单元格的相同位置,它们可以是任何大小写,最多可以包含 4 个单词。 列表示例

我在名为数据库的单独工作簿中有一个大约 14,000 个名称的命名范围(全名)。

我需要查看名称是否显示在数据范围列表中,如果是,则用名称填充列 C。

在此先感谢您的帮助。

示例代码:

Sub Full_Name()
    
    Dim iWs As Worksheet, iFn As Variant, lastrow As Long, iDB As Worksheet
    
    iFn = Range("'[Shadow Datafie Database.xlsx]EMCP'!Full_Name").Value
    Set iWs = ActiveWorkbook.Worksheets("EMCP")
    lastrow = iWs.UsedRange.Rows.Count + 1
    
    For i = 2 To lastrow
        If InStr(iWs.Cells(i, 2), iFn) > 0 Then
            iWs.Cells(i, 3) = iFn
        End If
    Next
    
End Sub

此代码可能对您有用:

它假定您的姓名列表位于名为Table1的 Excel 表中

Sub FindName()

    'Open the csv file containing your information - building, department, etc.
    Dim wrkBkSrc As Workbook
    Set wrkBkSrc = Workbooks.Open("<path to your file>\Numplan(11).csv")

    'A csv file will only contain a single sheet, so can reference it by sheet position - first and only.
    With wrkBkSrc.Worksheets(1)
        Dim DataRange As Range
        Set DataRange = .Range(.Cells(2, 2), .Cells(.Rows.Count, 2).End(xlUp))
    End With
    
'    *** OLD CODE ***
'    With ThisWorkbook.Worksheets("Sheet1")
'        Dim DataRange As Range
'        Set DataRange = .Range(.Cells(2, 2), .Cells(.Rows.Count, 2).End(xlUp))
'    End With
    
    'Open the database file and set reference to it.
    Dim wrkBk As Workbook
    Set wrkBk = Workbooks.Open("<path to your file>\Database.xlsx")
    
    'Set reference to the names table.
    'Note: This is an Excel table, not an Excel range.
    '      Press Ctrl+T to turn range into a table.
    Dim NameTable As ListObject
    Set NameTable = wrkBk.Worksheets("Database").ListObjects("Table1")
    
    'Only continue if there's data in the table.
    If Not NameTable.DataBodyRange Is Nothing Then
        Dim NameItm As Range
        Dim FoundItm As Range
        For Each NameItm In NameTable.DataBodyRange
            'Find the name within the DataRange.
            Set FoundItm = DataRange.Find( _
                What:=NameItm, _
                After:=DataRange.Cells(1, 1), _
                LookIn:=xlValues, _
                LookAt:=xlPart, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, _
                MatchCase:=False)
            
            'If it's found place the name in the next column along.
            If Not FoundItm Is Nothing Then
                FoundItm.Offset(, 1) = NameItm
            End If
        Next NameItm
    End If
    
End Sub

暂无
暂无

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

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