使用 VBA 复制和粘贴多个单元格

Copy and Paste multiple cells with VBA

我正在尝试自动执行 Excel 工作表中的宏。我在第一个工作表上有一个很大的 table,行数可变,我需要为主工作表的每一行创建一些“板”(具有特定数据的 5 行组)(发布在附图)。车牌需要像屏幕截图中那样显示,以便导出为 .pdf 文件(2 个在同一级别,直到最后一个)

这是我想出的代码,使用宏记录和其他发现的宏,并且已经为我工作(pdf 打印):

Sheets("Summary").Select
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
first_row = "A2"
sec_row = "F2"
For i = 1 To lastRow

Sheets("Foglio1").Select
Range("S3:V7").Select
Selection.Copy
Range("first_row:first_row+4").Select
ActiveSheet.Paste
Range("sec_row:sec_row+4").Select
ActiveSheet.Paste

i = i + 2
Next

在此之后,我有一个代码部分,我将所选区域导出为 pdf(简单且有效)。

好的,目前您的代码中有许多“我希望它能工作”类型的部分,现在问题可能多于答案。

您的输出 sheet“Foglio1”目前的格式似乎可以在六个位置接受“盘子”。如果您的意图是这六个应该来自主要sheet“摘要”的不同行,那么这比将每行的六个副本打印出来要复杂一些。

随着 sheet 之间的所有来回切换,值得使用一些 RangeWorksheet 变量来防止屏幕变得太忙。

有许多活动要分开:

  • 从主站获取“车牌”信息sheet
  • 适当格式化
  • 更新摘要sheet
  • 如果时间合适,输出为pdf

所以我的总体方案如下:

' set up plate locations in output sheet Array("A2","F2","A8",...)
' ---- set up range of records to scan (ScanRange) (only column A, other data by .Offset)
For Each ACell in ScanRange
    ' ---- get data from this record e.g.
    phone = ACell.Offset(0,5).Text
    ' ---- fill next plate (Range) in output sheet e.g.
    whichPlate = whichPlate + 1 ' & cycle
    Set plate = Range(plates(whichPlate))
    plate.Offset(1,0).Value = "Ph. " & phone 'etc.
    ' ---- send to pdf if appropriate
    ' ---- clean up output sheet if needed
Next ACell

' ---- send last batch to pdf

假设你的总结sheet是这样的

然后尝试

Option Explicit

Sub CreatePDF()

    Dim wb As Workbook, ws As Worksheet, wsPDF As Worksheet
    Dim iLastRow As Long, ar(1 To 5, 1 To 1), rng As Range
    Dim i As Long, r As Long, c As Integer, k As Integer
   
    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Summary")
    Set wsPDF = wb.Sheets("Foglio1")
    'wsPDF.Cells.Clear

    ' fixed
    ar(1, 1) = "Factory s.r.l."
    ar(2, 1) = "Ph. +39 0000 00000"
    ar(3, 1) = "Web www.website.net"
   
    iLastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
    r = 2 ' start row
    c = 1 ' column A
    For i = 2 To iLastRow
        ar(4, 1) = "JOB " & ws.Cells(i, "A")
        ar(5, 1) = "ORDER " & ws.Cells(i, "B")
       
        ' fill plate
        Set rng = wsPDF.Cells(r, c).Resize(5, 1)
        rng.Value2 = ar
       
        ' merge cells
        For k = 1 To 5
            With rng.Cells(k, 1).Resize(1, 4)
                .Merge
                .HorizontalAlignment = xlCenter
                .Font.Bold = True
            End With
        Next
        
        ' move to next plate
        If i Mod 2 = 0 Then
            c = 6 ' column F
        Else
            c = 1 ' column A
            r = r + 6
        End If
    Next
    MsgBox "Done"
End Sub