[英]VBA Transform Many Columns to Two - What am I doing wrong?
Hi I'm not very familiar with vba. 嗨,我对vba不太熟悉。 But I came up with the following to turn a spreadsheet with multiple columns into just two.
但是我想出了以下方法,可以将具有多列的电子表格变成只有两列。 Example shows a name with multiple items.
示例显示了一个包含多个项目的名称。 I need a row with the name for each item.
我需要为每个项目添加一行名称。
You can see the length of each row can change. 您可以看到每行的长度可以更改。 I do know how many rows.
我确实知道多少行。 I've made the following script but can't seem to get it to work.
我编写了以下脚本,但似乎无法使其正常工作。 Please any advice on how to fix is very helpful!
请任何有关如何修复的建议非常有帮助!
This is what I have: 这就是我所拥有的:
name1 | 名称1 | item1 |
item1 | item2 |
item2 | item3 |
item3 | item4
项目4
name2 | name2 | item5 |
item5 | item3 |
item3 | item19
项目19
This is what I need: 这就是我需要的:
name1 | 名称1 | item1
项目1
name1 | 名称1 | item2
item2
name1 | 名称1 | item3
项目3
name1 | 名称1 | item4
项目4
name2 | name2 | item5
项目5
name2 | name2 | item3
项目3
name2 | name2 | item19
项目19
Sub moveToRows()
Dim name As String, item as String,
Dim r As Double, c As Double, r2 As Double, l As Double
Sheets("Sheet1").Select
r = 1
c = 1
r2 = 1
Do While r < 5000
ActiveSheet.Cells(r, c).Select
name = ActiveCell.Value
l = ActiveRow.Length
Do While c <= l
item = ActiveCell.Offset(0, c)
Sheets("Sheet2").Range.Cells(r2, 1).Value = name
Sheets("Sheet2").Range.Cells(r2, 2).Value = item
c = c + 1
r2 = r2 + 1
Cells(r, c).Select
Loop
c = 1
r = r + 1
Loop
End Sub
I was able to solve the problem with the IsEmpty as suggested. 我能够按照建议使用IsEmpty解决问题。 Changed output location as see in variable oRow.
更改了输出位置,如变量oRow所示。
Sub moveToRows()
Dim name As String, item As String
Dim r As Double, oRow As Double
Range("A1").Select
oRow = 5000
For r = 1 To ActiveCell.End(xlDown).Row
Cells(r, 2).Select
name = ActiveCell.Offset(0, -1).Value
If IsEmpty(ActiveCell) Then
Cells(oRow, 1).Value = name
oRow = oRow + 1
End If
Do Until IsEmpty(Selection)
item = ActiveCell.Value
Cells(oRow, 1).Value = name
Cells(oRow, 2).Value = item
ActiveCell.Offset(0, 1).Select
oRow = oRow + 1
item = ""
Loop
Next
End Sub
This solution is much faster because: 此解决方案更快,因为:
Here you are: 这个给你:
Sub moveToRows()
Dim name As String, item As String
Dim shin As Worksheet
Dim shout As Worksheet
' Edit the sheet names here if needed
Set shin = ActiveWorkbook.Sheets("Sheet1")
Set shout = ActiveWorkbook.Sheets("Sheet2")
Dim r As Double, c As Double, r2 As Double, l As Double
r = 1
r2 = 1
Do
c = 1
name = shin.Cells(r, c)
If name = "" Then Exit Do
Do
c = c + 1
item = shin.Cells(r, c)
If item = "" Then Exit Do
shout.Cells(r2, 1).Value = name
shout.Cells(r2, 2).Value = item
r2 = r2 + 1
Loop
r = r + 1
Loop
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.