VBA循环到新创建的选项卡

时间:2017-09-19 16:18:19

标签: vba excel-vba excel

我正在尝试根据我输入的" Sheet1"选项卡,然后在创建所有工作表后将这些语句打印到PDF。我遇到了一个问题(请参阅下面的代码),其中创建的每个工作表都是将单元格A4中的数字保留在" Sheet 1"而不是向下移动行,以便每个新创建的工作表上的K1中的数字对应于" Sheet1"上的下一行。

Sub TEST()
'
' TEST Macro
'

'
    On Error Resume Next
    Dim MyCell As Range, MyRange As Range

    Set MyRange = Sheets("Sheet1").Range("A4")
    Set MyRange = Range(MyRange, MyRange.End(xlDown))

    With ThisWorkbook
        For Each MyCell In MyRange
            .Sheets("Sample").Copy After:=Sheets(Sheets.Count)
            .Sheets(Sheets.Count).Name = MyCell.Value

        Next

    Sheets("Sheet1").Select
    FinalRow = Cells(Row.Count, 1).End(xlUp).Row

        For x=4 to Final Row
            .Sheets("Sheet1").Range("A5").Copy _
            Destination:=Worksheets(Sheets.Count).Range("K1")

        Next


End With

Dim FolderPath As String

FolderPath = "XXX"

For I = 1 To Worksheets.Count

    Worksheets(I).ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath & "\" & _
    Worksheets(I).Name, openafterpublish:=True

        Next

MsgBox "All PDF's have been successfully exported"

End Sub

1 个答案:

答案 0 :(得分:0)

我已将With ThisWorkbook的代码重构为End With

我完全消除了With块,因为它不需要。

For Each MyCell In MyRange
    .Sheets("Sample").Copy After:=Sheets(Sheets.Count)
    .Sheets(Sheets.Count).Name = MyCell.Value
    .Sheets(MyCell.Value).Range("K1") = MyCell.Value  
Next