excel - 在excel vba中将多列堆叠成一列
问题描述
我有多列(15 到 16)的数据(见图片)。
它有一个数字,分为 3 列,例如。147被分成三列1、4、7和268被分成2、6、8。现在我想以如图所示的方式堆叠数据
为此,我尝试连接三列以生成单个数字,例如 1、4、7 组合成 147,2、6、8 组合成 268。我编写的代码给出了输出 148 和 268,但是它在它们之间有两个空列,如下所示。
我无法堆叠这些列以获得所需的输出。请建议任何直接从输入堆叠到所需输出的方法,或者对我当前的代码进行任何修改,以便我在连续列中获得串联数据。
注意:- 行数和列数是可变的而不是静态的。
Sub JoinAndCut()
Dim n As Long
Dim p, col As Long
Dim lastrow As Long
For p = 1 To 25 Step 3
lastrow = ThisWorkbook.Worksheets(2).Cells(Rows.count, p).End(xlUp).Row '<== To Count number of rows in each column
For n = 2 To lastrow
Cells(n, p).Offset(, 25).Value = Cells(n, p).Value & Cells(n, p + 1).Value & Cells(n, p + 2).Value ' <=== Offset by 25 values so as they dont overlap the input
Next n
Next p
End Sub
Sub JoinAndCut()
Dim n As Long
Dim p, col As Long
Dim lastrow As Long
For p = 1 To 25 Step 3
lastrow = ThisWorkbook.Worksheets(2).Cells(Rows.count, p).End(xlUp).Row '<== To Count number of rows in each column
For n = 2 To lastrow
Cells(n, p).Offset(, 25).Value = Cells(n, p).Value & Cells(n, p + 1).Value & Cells(n, p + 2).Value ' <=== Offset by 25 values so as they dont overlap the input
Next n
Next p
End Sub
解决方案
你可以试试这个:
Sub JoinAndCut()
Dim n As Long
Dim p, col As Long
Dim lastrow As Long, lastrowstack As Long
For p = 1 To 25 Step 3
lastrow = ThisWorkbook.Worksheets(2).Cells(Rows.Count, p).End(xlUp).Row '<== To get row number in each column
lastrowstack = ThisWorkbook.Worksheets(2).Cells(Rows.Count, 26).End(xlUp).Row '<== To get row number in in the stacked column
For n = 2 To lastrow
Cells(n + lastrowstack - 1, 26).Value = Cells(n, p).Value & Cells(n, p + 1).Value & Cells(n, p + 2).Value ' <=== Starting in column 26 so as they dont overlap the input
Next n
Next p
End Sub
假设你有这样的事情:
然后将它们组合并堆叠在 Z 列(又名第 26 列)中,前 36 行将如下所示。
推荐阅读
- java - 在文本属性中使用 HTML 在 JLabel 中插入图像
- r - 将数组算法包装到函数中的问题
- spring - 不匹配此类型名称
- android - 如何将我的 dialogFragment 显示为圆角?
- php - 如何在不知道键的情况下读取嵌套数组值?
- javascript - 通过将变量传递给jquery来获取数据而不重新加载
- html - 为什么我的组合框不显示任何内容?
- file - Xamarin.android - 将 .jpg 复制到共享文件夹
- azure - 如何使用 ARM 模板在 Linux 上创建 Azure Functions 使用计划?
- python - 根据最大值的长度从python列出的字典中查找项目?