Иллюстрация применения функции Split Иногда приходится разбивать на части линейный список элементов, который разделён запятыми. Например, когда вводишь перечень материалов, цветов и т.п., а их надо занести в таблицу. Причём каждый элемент в отдельную запись. Писал я как-то давно такую функцию. И вот недавно наткнулся на похожий случай. Может кому-то пригодится (Admin)
'--------------------------------------------------------------------------------------- ' Procedure : BreakListIntoLineItems ' Author : Daniel Pineault, CARDA Consultants Inc. ' Website : http://www.cardaconsultants.com ' Purpose : Take a delimited list of items and break it into line items ' Copyright : The following is release as Attribution-ShareAlike 4.0 International ' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/ ' Req'd Refs: None required ' ' Input Variables: ' ~~~~~~~~~~~~~~~~ ' sList : List to split into line items ' sDelim : Item delimiter character(s), if not specified a comma will be assumed/used ' ' Usage: ' ~~~~~~ ' BreakListIntoLineItems("My Book, My Book for Mac, My Book Duo, My Book") ' ' Revision History: ' Rev Date(yyyy-mm-dd) Description ' ************************************************************************************** ' 1 2020-09-23 Initial Release '--------------------------------------------------------------------------------------- Public Sub BreakListIntoLineItems(ByVal sList As String, _ Optional sDelim As String = ",") Dim aList Dim i As Long On Error GoTo Error_Handler aList = Split(sList, sDelim) For i = 0 To UBound(aList) Debug.Print Trim(aList(i)) Next i Error_Handler_Exit: On Error Resume Next Exit Sub
Error_Handler: MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _ "Error Number: " & Err.Number & vbCrLf & _ "Error Source: BreakListIntoLineItems" & vbCrLf & _ "Error Description: " & Err.Description & _ Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _ , vbOKOnly + vbCritical, "An Error has Occurred!" Resume Error_Handler_Exit End Sub Пример использованияBreakListIntoLineItems("My Book, My Book for Mac, My Book Duo, My Book, _ WD easystore Desktop, My Book Duo, My Passport Wireless, My Passport Ultra Metal, _ My Passport Ultra (WD Backup), My Passport for Mac, My Passport Wireless Pro, My Passport, _ My Passport for Mac, WD easystore Portable, My Passport SSD, My Passport Ultra, My Passport Wireless SSD, _ My Passport Ultra (USB-C), My Passport Ultra for Mac (USB-C), My Passport ")
Получится
My Book My Book for Mac My Book Duo My Book WD easystore Desktop My Book Duo My Passport Wireless My Passport Ultra Metal My Passport Ultra (WD Backup) My Passport for Mac My Passport Wireless Pro My Passport My Passport for Mac WD easystore Portable My Passport SSD My Passport Ultra My Passport Wireless SSD My Passport Ultra (USB-C) My Passport Ultra for Mac (USB-C) My Passport Go
Взято здесь VBA – Break List Into Line Items Просмотров: 1790
Ваш коментарий будет первым | | |