我的数据看起来像这样,垂直方向非常非常长。
#1, name1, number1
#2, name2, number2
#3, name3, number3
...
#2000, name2000, number2000
我想重新格式化为适合每个打印页面的 2 或 3 组列。像这样
#1, name1, number1 #5 #9
#2, name2, number2 #6 #10
#3, name3, number3 #7 #11
#4, name4, number4 #8 #12
end of page 1
#13 #17 #21
#14 #18 #22
#15 #19 #23
#16 #20 #24
等等。
我以前从未编写过 VB 代码,但我尝试调整我找到的一些现有代码来执行此操作,但遇到了错误。我计算了每页所需的行数,结果是 36。
Sub joeycol()
Dim count As Integer
count = 1
Dim desRow As Long
desRow = 1
Dim desColumn As Long
desColumn = 1
Dim srcRow As Long
Dim endRow As Long
endRow = 577
Dim srcColumn As Long
Dim wks As Worksheet
Set wks = Worksheets.Add
Dim x As Long
For srcRow = 1 To endRow
If count = 4 Then
count = 1
desRow = desRow - 36
End If
For srcColumn = 1 To 3
x = srcColumn * count
Cells(desRow, x) = rng.Cells(srcRow, srcColumn)
Next
count = count + 1
desRow = desRow + 1
Next
子目录结束
这一行一直给我错误 1004,而且错误消息没有给我任何线索 :(
Cells(desRow, x) = rng.Cells(srcRow, srcColumn)
我在这里读过一些答案,可能有更好的方法可以通过复制范围而不是像我一样循环来实现,但是我没有时间学习,因为我需要尽快完成这项工作,如果有人能帮助我研究这个问题,我将不胜感激。
非常感谢。
答案1
1004 错误通常是由于引用了不存在的对象(行、单元格、列、范围等)(在当时)。
要开始诊断,请在出现错误的行上放置一个断点,然后逐步检查 desRow、srcColumn、srcRow、rng 和 count 的值(通过 Watches)。在循环的每次迭代中检查它们,并确保它们引用的是有效对象(当时确实存在)。
答案2
这将在只有 36 行长的页面中沿列插入分页符。这意味着每页将有 72 个 3 列条目。
Sub test()
Dim wsOriginal As Worksheet
Set wsOriginal = ActiveSheet
Dim wsDest As Worksheet
Set wsDest = Worksheets.Add
Dim lastrow As Integer
lastrow = wsOriginal.Cells(Rows.count, "a").End(xlUp).Row
Dim numSections As Integer
numSections = lastrow / 36
Dim i As Integer
Dim j As Integer
Dim k As Integer
k = 0
For i = 1 To lastrow
If i > 36 * (k + 1) Then
k = k + 1
End If
For j = 1 To 3
wsDest.Cells((i - (36 * k)), j + (k * 4)) = wsOriginal.Cells(i, j)
Next
Next
Dim lastCol As Integer
lastCol = wsDest.Cells(1, Columns.count).End(xlToLeft).Column
Dim numPages As Integer
numPages = lastCol / 8
For Z = 1 To numPages
wsDest.Columns(8 * Z).PageBreak = xlPageBreakManual
Next
End Sub