2 个 Excel 表:1)工作文件,2)数据文件。如果数据匹配,需要更新工作文件中的“城市”列。请使用Excel VBA

问题描述 投票:0回答:1

当我运行这个宏时没有任何反应,它不会附加地址表的城市列。但宏执行没有错误。

我希望当将数据与地址“城市名称”进行比较时,它会更新相应的“城市”列。我的宏:

Sub UpdateCityNames()
    Dim wsLugar As Worksheet
    Dim wsSiudad As Worksheet
    Dim lastRowLugar As Long
    Dim lastRowSiudad As Long
    Dim i As Long, j As Long
    Dim townOrCityName As String
    
    ' Set the worksheets
    Set wsLugar = ThisWorkbook.Sheets("Lugar")
    Set wsSiudad = ThisWorkbook.Sheets("Siudad")
    
    ' Find the last row with data in the Siudad and Lugar sheets
    lastRowLugar = wsLugar.Cells(wsLugar.Rows.Count, "H").End(xlUp).Row
    lastRowSiudad = wsSiudad.Cells(wsSiudad.Rows.Count, "A").End(xlUp).Row
    
    ' Loop through each row in Siudad sheet
    For i = 1 To lastRowSiudad
        townOrCityName = wsSiudad.Cells(i, 1).Value ' Town or city name
        
        ' Loop through each row in Lugar sheet
        For j = 1 To lastRowLugar
            ' Check if the town/city name exists in the address column
            If InStr(1, wsLugar.Cells(j, 1).Value, townOrCityName, vbTextCompare) > 0 Then
                ' Append town/city name to the city column
                wsLugar.Cells(j, 2).Value = townOrCityName
            End If
        Next j
    Next i
End Sub
excel vba
1个回答
0
投票

我觉得你正在尝试重新发明

VLookup()
,让我告诉你我的意思:我创建了两张纸(“Ciudad”和“Lugar”),并且我使用
VLookup()
进行填充以城镇名称,基于邮政编码(我相信你正在做类似的事情)。

“Ciudad”表:
enter image description here

“卢格”表:
enter image description here

对应的

VLookup()
公式:

=VLOOKUP(Lugar!B1;Ciudad!$A$1:$B$2;2;FALSE)

请注意,您的 table_array 是基于绝对地址的:“ $ A $ 1: $ B $ 2”

© www.soinside.com 2019 - 2024. All rights reserved.