繁体   English   中英

使用第二个 Excel 工作簿作为 VBA 中的表

[英]Using a second Excel workbook as a table in VBA

想知道是否可以使用第二个工作簿作为表格来获取类似于 vlookup 的匹配数据而不使用公式。

示例:工作簿 1 我想通过使用工作簿 2 查看列 S(港口城市)来填写 R 列(港口代码),工作簿 2 在 D 列中有城市列表,港口代码我想在列中填写工作簿 1一个。

我知道我可以使用 Vlookup,但如果可以的话,我会尽量避免这样做。 我在想这样的事情,但这似乎只看第二个工作表的第一行。 任何帮助或推动正确的方向将不胜感激。

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

不确定我是否完全理解您的要求,但我认为您想进行部分搜索。 在这种情况下, Instr可能会有所帮助。 我不认为使用两个工作簿是有用的,但让我们按照你的方式去做。 这就是我想要的 go :

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

根据工作簿的大小,这种方法可能不是最有效的。 如果太耗时,您可以使用 go 和.Find

暂无
暂无

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

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