是否可以遍历工作表并创建字符串?

问题描述 投票:0回答:1

所以我正在创建一个宏,它将通过下拉列表中的选项准备临时文件中的所有数据,然后以PDF格式打印。

我在最后一部分遇到麻烦,我想创建一个循环,该循环将循环所有工作表,并为每个工作表的所有名称示例提供一个String,并在第四个字母上加上Temp。

这是我拥有的代码:

Set DV_Cell = Range("C5")

    ExcelPath = ThisWorkbook.Path

'Set range as the List for the dropdown list
    Set rgDV = ThisWorkbook.Worksheets("Sheet1").Range("S16:S23")

'Loop that changes the value of the C5 then copys the data
    For Each cell In rgDV.Cells
        DV_Cell.Value = cell.Value

        Sheets.Add.Name = "Temp" & DV_Cell.Value
        SheetName = ActiveSheet.Name
        ThisWorkbook.Worksheets("Sheet2").Cells.Copy
        ThisWorkbook.Worksheets(SheetName).Paste
    Next

        ThisWorkbook.Worksheets("Temp").ExportAsFixedFormat _
            Type:=xlTypePDF, _
            Filename:=ExcelPath & DV_Cell.Value, _
            Quality:=xlQualityStandard, _
            IncludeDocProperties:=False, _
            IgnorePrintAreas:=False, _
            OpenAfterPublish:=False

这是我必须删除Temp文件的代码,可能与获取该字符串所需的代码相似:

For Each Sheet In ThisWorkbook.Worksheets

    StrS = Sheet.Name
     If Left(StrS, 4) = "Temp" Then
          Sheet.Delete
     End If

Next Sheet
excel vba
1个回答
0
投票

创建所有临时表后,将按字母顺序对其进行排序。然后,它将循环浏览工作簿中的所有工作表,并选择前四个字母为“临时”的工作表。一旦全部选定,它将立即全部打印到PDF文件。

'Order worksheets alphabetically so they print in order
Dim x As Integer, y As Integer
For x = 1 To Worksheets.Count
    For y = x To Worksheets.Count
        If UCase(Sheets(y).Name) < UCase(Sheets(x).Name) Then
            Sheets(y).Move before:=Sheets(x)
        End If
    Next
Next

Dim ws As Worksheet

Dim replaceSelection As Boolean
replaceSelection = True

For Each ws In ThisWorkbook.Sheets
    If Left(ws.Name, 4) = "Temp" Then
        'This allows for selecting multiple sheets
        ws.Select Replace:=replaceSelection
        replaceSelection = False
    End If
Next ws

'Once all the Temp sheets have been selected you can print all at once to a PDF.
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
    Filename:=excelpath & "\TempSheets.pdf", _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=False, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False

希望这就是您想要的。祝您的项目好运!

© www.soinside.com 2019 - 2024. All rights reserved.