VBA для извлечения ссылки на переменную из строки, а затем поиска - PullRequest
0 голосов
/ 04 марта 2019

У меня проблемы с извлечением ссылки из строки и выполнением поиска после.

Итак, у меня есть таблица поиска на другом листе;

Col A |Col B

13453 |Место 1

13099 |Место 2

125515 |Место 3

12357 |Место 4

121671 |Место 5

И у меня есть список ссылок на платежи, которые входят в лист импорта, подобный этому, с учетом различий в длине;

CA13453 / 130

CA13099 / 33

CA125515 / 75

CA12357 / 1

CA121671 / 54

Я хотел бы помочь VBA найти первые 5 или шесть чиселссылку на платеж, сравните ее с таблицей поиска, затем вставьте название места в следующем столбце.После запуска кода вкладка импорта будет выглядеть так:

Col A |Col B на листе импорта

CA13453 / 130 |Место 1

CA13099 / 33 |Место 2

CA125515 / 75 |Место 3

CA12357 / 1 |Место 4

CA121671 / 54 |Место 5

Дайте мне знать, если вам нужна дополнительная информация и большое спасибо за вашу помощь!

1 Ответ

0 голосов
/ 04 марта 2019

Вот два варианта для вас.Первый - это макрос, который будет обрабатывать каждую строку в листе импорта.Во-вторых, используется функция, и вам придется помещать эту функцию в каждую строку для получения данных о местоположении.

Во-первых, макрос для обработки каждой строки в листе импорта.Это может быть вызвано нажатием alt + f8 или добавлением командной кнопки в вашу книгу, которая выполняет макрос.

Sub GetLocationNames()

LocationShtNm = "Locations"  ' <---- Name of the sheet that has the location data
ImportShtNm = "Import"  ' <---- Name of the sheet that has the payment data
LocationStartRow = 2 ' <----- Change to the row that has the first row of location data in the Locations sheet
ImportStartRow = 2 ' <----- Change to the row that has the first row of payment data in the Imported data sheet
LocationKeyCol = 1 ' <----- Change to column that has the location names in the locations sheet
LocationNamesCol = 2 ' <----- Change to column that has the location names in the locations sheet
ImportKeyCol = 1 ' <----- Change to the column that has the payment number in the import sheet
ImportLocCol = 2 ' <----- Change to the column that has the location in the import sheet

Set LocationSheet = ActiveWorkbook.Sheets(LocationShtNm)
Set ImportSheet = ActiveWorkbook.Sheets(ImportShtNm)

'* Get the range for the traveller data
LocationLastRow = LocationSheet.UsedRange.Rows.Count
ImportLastRow = ImportSheet.UsedRange.Rows.Count

' Loop through the import data one row at a time
For i = ImportStartRow To ImportLastRow
    LocationKey = Mid(ImportSheet.Cells(i, ImportKeyCol), 3)
    SlashLoc = InStr(LocationKey, "/")
    LocationKey = Left(LocationKey, SlashLoc - 1)

    ' Loop through the location data and find the location
    FoundLoc = False
    For j = LocationStartRow To LocationLastRow
        If Trim(LocationSheet.Cells(j, LocationKeyCol)) = LocationKey Then
            FoundLoc = True
            CurrLocation = LocationSheet.Cells(j, LocationNamesCol).Value
            Exit For
        End If
    Next j

    If FoundLoc = True Then
        ImportSheet.Cells(i, ImportLocCol) = CurrLocation
    Else
        ImportSheet.Cells(i, ImportLocCol) = "Not Found"
    End If

Next i

End Sub

Вторая функция - это функция.Вам нужно будет поместить это в ячейку в каждой строке листа импорта, например:

=GetLocationName(A2) ' Where A2 would have a payment reference number

Вот макрос, который реализует функцию.

Function GetLocationName(CellIn)

LocationShtNm = "Locations"  ' <---- Name of the sheet that has the location data
ImportShtNm = "Import"  ' <---- Name of the sheet that has the payment data
LocationStartRow = 2 ' <----- Change to the row that has the first row of location data in the Locations sheet
ImportStartRow = 2 ' <----- Change to the row that has the first row of payment data in the Imported data sheet
LocationKeyCol = 1 ' <----- Change to column that has the location names in the locations sheet
LocationNamesCol = 2 ' <----- Change to column that has the location names in the locations sheet
ImportKeyCol = 1 ' <----- Change to the column that has the payment number in the import sheet
ImportLocCol = 2 ' <----- Change to the column that has the location in the import sheet

Set LocationSheet = ActiveWorkbook.Sheets(LocationShtNm)
Set ImportSheet = ActiveWorkbook.Sheets(ImportShtNm)

'* Get the range for the traveller data
LocationLastRow = LocationSheet.UsedRange.Rows.Count
ImportLastRow = ImportSheet.UsedRange.Rows.Count

LocationKey = Mid(CellIn.Value, 3)
SlashLoc = InStr(LocationKey, "/")
LocationKey = Left(LocationKey, SlashLoc - 1)

' Loop through the location data and find the location
FoundLoc = False
For j = LocationStartRow To LocationLastRow
    If Trim(LocationSheet.Cells(j, LocationKeyCol)) = LocationKey Then
        FoundLoc = True
        CurrLocation = LocationSheet.Cells(j, LocationNamesCol).Value
        Exit For
    End If
Next j

If FoundLoc = True Then
    GetLocationName = CurrLocation
Else
    GetLocationName = "Not Found"
End If


End Function

Рабочий лист местоположения:enter image description here

Рабочий лист импорта: enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...