Excel VBA开发需求:按区域编号生成连续邮政编码区间
Excel VBA 生成连续邮政编码区间(仅区域编号变更时生成新行)
需求说明
根据A列邮政编码与B列区域编号数据,生成连续邮政编码区间,仅在区域编号变更时生成新行。现有代码会为每个邮编单独生成一行,不符合需求。
原始数据
| A列(邮政编码) | B列(区域编号) |
|---|---|
| 00210 | 1 |
| 00544 | 1 |
| 00548 | 2 |
| 00840 | 3 |
| 01101 | 1 |
| 01200 | 2 |
期望输出
| A列(邮编区间) | B列(区域编号) |
|---|---|
| 00210-00547 | 1 |
| 00548-00839 | 2 |
| 00840-01100 | 3 |
| 01101-01199 | 1 |
问题代码
Sub try_this() Dim y As Long, lastrow As Long, sht As Worksheet Set sht = Worksheets("put_your_sheet_name_here") 'change this 'get last row lastrow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row For y = 1 To lastrow - 1 With sht.Cells(y, 1) 'create range in 3rd column .Offset(0, 2).Value = .Value & "-" & .Offset(1, 0).Value - 1 'copy range name to 4th column .Offset(0, 3).Value = .Offset(0, 1).Value End With Next End Sub
修正后代码
Sub GeneratePostalCodeRanges() Dim sht As Worksheet Dim lastRow As Long, startRow As Long, currentRow As Long Dim startPostal As String, endPostal As String Dim currentRegion As Integer ' 替换为你的目标工作表名称 Set sht = Worksheets("put_your_sheet_name_here") lastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row ' 初始化跟踪变量 startRow = 1 currentRegion = sht.Cells(startRow, 2).Value startPostal = sht.Cells(startRow, 1).Value ' 遍历数据,按区域分组生成区间 For currentRow = 2 To lastRow ' 区域编号变更时,生成上一组的区间 If sht.Cells(currentRow, 2).Value <> currentRegion Then ' 计算结束邮编:当前行邮编减1,保持5位带前导零格式 endPostal = Format(CLng(sht.Cells(currentRow, 1).Value) - 1, "00000") ' 将结果写入C、D列(可根据需求调整输出列位置) sht.Cells(startRow, 3).Value = startPostal & "-" & endPostal sht.Cells(startRow, 4).Value = currentRegion ' 更新跟踪变量,开始新区域的记录 startRow = currentRow currentRegion = sht.Cells(startRow, 2).Value startPostal = sht.Cells(startRow, 1).Value End If Next currentRow ' 处理最后一组区域数据 If startRow <= lastRow Then endPostal = Format(CLng(sht.Cells(lastRow, 1).Value) - 1, "00000") sht.Cells(startRow, 3).Value = startPostal & "-" & endPostal sht.Cells(startRow, 4).Value = currentRegion End If End Sub
关键逻辑说明
- 分组跟踪:通过
startRow记录当前区域的起始行,currentRegion记录当前区域编号,startPostal记录当前区域的起始邮编。 - 区间计算:当区域编号变化时,用下一行的邮编减1作为当前区域的结束邮编,通过
Format函数确保结果为5位带前导零的字符串,避免丢失邮编的前导零。 - 收尾处理:遍历结束后单独处理最后一组区域,确保所有数据都被转换为区间格式。
内容的提问来源于stack exchange,提问作者Nancy Sellers
相关产品推荐
相关产品推荐

