首页 > 解决方案 > 打印 VBA 时为每一行编号

问题描述

我在两列(myrange1 和 myrange2)中找到匹配项,将它们填充到 sheet2 的第三列(“R”)中。我的范围从“R”列打印到 PDF 就好了,但我希望每一个都在 PDF 上按顺序编号,即 1、2、3、4 等。非常感谢帮助。VBA 也很新。

Sub matchcopy()
    Dim myrange1 As Range, myrange2 As Range, cell As Range

    With Sheets("Sheet1")
        Set myrange1 = .Range("A1", .Range("A" & Rows.Count).End(xlUp))
    End With

    With Sheets("Sheet2")
        Set myrange2 = .Range("A1", .Range("A" & Rows.Count).End(xlUp))
    End With

    For Each cell In myrange1
        If Not IsError(Application.Match(cell.Value, myrange2, 0)) Then  
            'cell.Value, myrange2, 0
            cell.Copy
            Sheet2.Range("R5000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
        Else
            'MsgBox "no match is found in range"
        End If
    Next cell

    Columns("R:R").EntireColumn.AutoFit
    Call Set_PrintRnag
End Sub


Sub Set_PrintRnag()
    Dim LstRw As Long
    Dim Rng As Range

    LstRw = Cells(Rows.Count, "R").End(xlUp).Row
    Set Rng = Range("R1:R" & LstRw)

    With ActiveSheet.PageSetup
        .LeftHeader = "&C &B &20 Cohort List Report : " & Format(Date, 
    "mm/dd/yyyy")
    End With

    Rng.ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & _
      "\CohortList " & " " & Format(Date, "mm-dd-yyyy") & ".pdf", _
      Quality:=xlQualityStandard, IncludeDocProperties:=True, _
      IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

标签: excelvba

解决方案


您是否需要 VBA 脚本来实现您想要的目标?如果您只是想比较两个值并在 R 列中输出结果,您应该可以使用 IF 函数: https: //support.office.com/en-us/article/if-function- 69aed7c9-4e8a-4755-a9bc-aa8bbff73be2

如果您想要对结果进行顺序编号,我建议您将数字放在相邻列中并探索 COUNTA 函数: https: //support.office.com/en-us/article/counta-function-7dc98875-d5c1-46f1 -9a82-53f3219e2509

如果您确实需要 VBA 脚本格式,您可以先使用 Excel 函数执行此操作,然后再录制宏。使创建实际的 VBA 语法更容易一些!https://support.office.com/en-us/article/automate-tasks-with-the-macro-recorder-974ef220-f716-4e01-b015-3ea70e64937b


推荐阅读