简体   繁体   中英

Merge 2 columns and find text VBA

I have one table and one file. I can find the text which is in specific place in file inside the table. However, the texts are not unique all the time, so I decided to combine 2 cells in file and try to find in table. unless, I cannot find a way to combine 2 columns in table to match it with combined 2 cells in file.

Below you may see example table.

在此处输入图像描述 my aim is adding date in cell next cell of Units. So I try to find A1234 instead of 1234 due to 1234 not unique.

FindString = wb.Sheets("1").Range("E4").Value & wb.Sheets("1").Range("E5").Value
If Trim(FindString) <> "" Then
    With Wb2.Sheets("Sheet1").Range("A:A") 'this section need to be amended and need combine column A&B
        Set Rng = .Find(What:=FindString, _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlValues, _
                        LookAt:=xlWhole, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
                
        If Not Rng Is Nothing Then
             Rng.Offset(0, 1).Value = wb.Sheets("1").Range("I4") ' if column A&B combining completed then next cell probably will not work
           
        Else
            MsgBox "Nothing found in the list"
        End If

This is similar to the variant strategy mentioned in the comments-- Try looping through your data with a For loop and an If Statement looking for both values to match. Here's an example code that shows the concept

Sub test()
    Dim s As Worksheet, findstring1 As String, findstring2 As String
    Dim firstrow As Integer, lastrow As Integer, i As Integer
    
    Set s = Sheets("test") 
    
    findstring1 = "A "'replace this with the Customer reference (what to search for) 
    findstring2 = "1234" 'replace this with the unit reference
    
    firstrow = 2  ' row number for first cell with data
    lastcell = s.Cells(2, 1).End(xlDown).Row  'find last cell row number (end of data)
    
        For i = firstrow To lastcell
        
            If s.Cells(i, 1) = findstring1 And s.Cells(i, 2) = findstring2 Then
            'do something with found values
            End If
            
        Next i
    
    End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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