簡體   English   中英

合並 2 列並找到文本 VBA

[英]Merge 2 columns and find text VBA

我有一張桌子和一個文件。 我可以在表格內的文件中找到特定位置的文本。 但是,文本並非一直都是唯一的,所以我決定在文件中合並 2 個單元格並嘗試在表格中查找。 除非,我找不到一種方法來組合表中的 2 列以將其與文件中組合的 2 個單元格匹配。

您可能會在下面看到示例表。

在此處輸入圖像描述 我的目標是在單元格的下一個單元格中添加日期。 所以我嘗試找到 A1234 而不是 1234,因為 1234 不是唯一的。

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

這類似於評論中提到的變體策略——嘗試使用 For 循環和 If 語句遍歷您的數據,以查找要匹配的兩個值。 這是一個顯示概念的示例代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM