简体   繁体   中英

Using a second Excel workbook as a table in VBA

Wondering if it's possible to use a second workbook as a table to grab matching data similar to a vlookup without using the formula.

Example: Workbook 1 I want to fill in Column R (Port Code) by looking at Column S (Port City) by using Workbook 2 which has a list of Cities in column D and the Port code I want to fill in workbook 1 in column A.

I know I could use a Vlookup but trying to avoid doing that if I can. I was thinking of something like this but this only appears to look at the first line of the second worksheet. Any help or push in the right direction would be appreciated.

Dim lr As Long, lr1 As Long, i As Long
Dim LineMaster As Workbook
Dim ls As Worksheet
Dim di As Workbook
Dim td As Worksheet

Set td = di.Worksheets(1)
Set ls = LineMaster.Worksheets(1)
lr = ls.Range("I" & ls.Rows.Count).End(xlUp).Row
    
        For i = 2 To lr
            If ls.Range("S" & i).Value Like "" Then
               ls.Range("R" & i).Value = ""
               
            ElseIf ls.Range("N" & i).Value = Left(td.Range("D" & i).Value, 4) Then 
                   ls.Range("N" & i).Value = td.Range("A" & i).Value
               
        Else
        End If
        Next i

Not sure I completely understood your request, but I think you want to do a partial search. In this case, the Instr might be helpful. I don't think using two workbooks is useful but let's do it your way. Here's what I would go with:

Sub PartialSearch()

Dim lr As Long, lr1 As Long, i As Long, j As Long
Dim lr2 As Long
Dim LineMaster As Workbook
Dim ls As Worksheet
Dim di As Workbook
Dim td As Worksheet

Set LineMaster = ThisWorkbook 'Workbook to fill
Set ls = LineMaster.Worksheets(1) 'Worksheet to fill
Set di = Workbooks.Open(your_workbook) 'Indicate the path of the workbook
Set td = di.Worksheets(1)

lr = ls.Range("S" & ls.Rows.Count).End(xlUp).Row 'Last row of the column S (where cities are already mentioned)
lr2 = td.Range("D" & di.Rows.Count).End(xlUp).Row

        For i = 2 To lr
            For j = 2 To lr2
                If ls.Range("R" & i).Value = "" Then 'If the cell in column R is empty
                    If InStr(1, ls.Range("S" & i).Value, td.Range("D" & j).Value) > 0 Then 'Then the macro looks for a partial search in the other workbook
                        ls.Range("R" & i).Value = td.Range("A" & j).Value 'If the value is found, then the port code is written (change the column A if needed)
                    End If
                End If
            Next j
        Next i
        
        
End Sub

Depending on the size of your workbook, this approach might not be the most effective. If it's too time consuming, you could go with .Find .

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