VBA如何拼接多个范围生成内存新范围 跳过空行且不写入工作表
VBA 三列范围按行拼接内存实现方案
VBA 完全可以实现该需求,全程通过内存数组运算完成,不需要将结果写入工作表,支持任意行数适配、自动跳过全空白行,拼接结果直接存储在变量中。
实现代码
' 三个单列范围按行拼接,返回纵向二维内存数组 Function ConcatMultiRowRanges(rngCol1 As Range, rngCol2 As Range, rngCol3 As Range, Optional Sep As String = "-") As Variant Dim arrCol1, arrCol2, arrCol3, resultArr Dim rowIdx As Long, validRowCount As Long Dim currentRowStr As String Dim isRowBlank As Boolean ' 校验三个输入范围行数一致 If rngCol1.Rows.Count <> rngCol2.Rows.Count Or rngCol2.Rows.Count <> rngCol3.Rows.Count Then ConcatMultiRowRanges = CVErr(xlErrValue) Exit Function End If ' 批量将范围值读入内存,比逐单元格读取效率高10~100倍 arrCol1 = rngCol1.Value arrCol2 = rngCol2.Value arrCol3 = rngCol3.Value ' 预分配最大可能长度的结果数组 ReDim resultArr(1 To UBound(arrCol1, 1), 1 To 1) validRowCount = 0 ' 逐行处理 For rowIdx = 1 To UBound(arrCol1, 1) ' 判断当前行三列是否全空白(自动忽略首尾空格) isRowBlank = (Trim(CStr(arrCol1(rowIdx, 1))) = "" _ And Trim(CStr(arrCol2(rowIdx, 1))) = "" _ And Trim(CStr(arrCol3(rowIdx, 1))) = "") If Not isRowBlank Then validRowCount = validRowCount + 1 currentRowStr = CStr(arrCol1(rowIdx, 1)) & Sep & CStr(arrCol2(rowIdx, 1)) & Sep & CStr(arrCol3(rowIdx, 1)) resultArr(validRowCount, 1) = currentRowStr End If Next rowIdx ' 无有效数据时返回空数组 If validRowCount = 0 Then ConcatMultiRowRanges = Array() Exit Function End If ' 裁剪数组到实际有效行数 ReDim Preserve resultArr(1 To validRowCount, 1 To 1) ConcatMultiRowRanges = resultArr End Function
调用示例
Sub Demo() Dim concatResult As Variant ' 传入三列对应的数据源范围,可根据实际表格修改区域地址 Set col1 = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row) Set col2 = Range("B2:B" & Cells(Rows.Count, "B").End(xlUp).Row) Set col3 = Range("C2:C" & Cells(Rows.Count, "C").End(xlUp).Row) ' 拼接结果直接存入变量,无任何工作表写入操作 concatResult = ConcatMultiRowRanges(col1, col2, col3) ' 测试:在立即窗口打印结果(按Ctrl+G可调出立即窗口) Dim i As Long For i = LBound(concatResult, 1) To UBound(concatResult, 1) Debug.Print concatResult(i, 1) Next i ' 对应示例数据源输出: ' The-Ball-Park ' The-Train-Station ' The-Fast-Lane End Sub
功能说明
- 无工作表写入操作:所有运算在内存中完成,结果直接保存在变量中,符合需求
- 自动跳过空行:判断空值时自动去除单元格首尾空格,避免无意义空格被识别为有效内容
- 行数自适应:不需要手动指定遍历行数,自动适配传入范围的总行数
- 自定义分隔符:默认使用
-作为拼接分隔符,可在调用时给第4个参数传入自定义分隔符 - 输入校验:如果传入的三个范围行数不一致,直接返回值错误,避免异常结果
内容的提问来源于stack exchange,提问作者Finntech
相关产品推荐
相关产品推荐

