我该如何重新编码,以便它可以遍历工作簿中的特定工作表

时间:2019-04-05 19:22:18

标签: vba loops

我有一个宏,需要循环浏览特定的工作表,但是我通过网上找到的许多示例构建了代码。因此,我不太确定在哪里或如何设置循环,并且我也确定我将不得不更改整个代码的设置方式。我真的根本没有编码知识。 eep。

Sub datatransfer()


Application.ScreenUpdating = False
Dim copySheet As Worksheet 

Dim pasteSheet As Worksheet

Set copySheet = Worksheets(ActiveSheet.Name)

Set pasteSheet = Worksheets("CMICIMPORT")

copySheet.Range("A100:AA124").Copy

pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues

Application.CutCopyMode = False

Application.ScreenUpdating = True

MsgBox "Data was copied over to the CMICIMPORT tab successfully", vbInformation, ActiveSheet.Name

Range("M4").Select

    With Selection.Font

        .Color = -11489280

        .TintAndShade = 0

    End With

End Sub

我必须在当前正在使用的每张工作表上运行上面的代码,而不是能够运行宏,并且该代码可以在我的所有薪资选项卡上运行。另外,如果这样可以更轻松地为我提供帮助,那么我的标签也会被命名为工资单(1),工资单(2)等等,直到工资单(200)。

2 个答案:

答案 0 :(得分:0)

这是一个快速又肮脏的解决方案,但仍然可以使用。

首先声明应该在名为Array()的{​​{1}}中循环的工作表。如果它们确实为200,则最好创建某种循环或从设置工作表中读取它们。无论如何,这是工作的一部分:

specificWorksheets

在注释Sub TestMe() Dim specificWorksheets As Variant specificWorksheets = Array("payroll (3)", "payroll (1)", "payroll (2)") Dim wks As Worksheet For Each wks In ThisWorkbook.Worksheets If valueInArray(wks.Name, specificWorksheets) Then wks.Activate 'Do your stuff, writing before... End If Next End Sub Public Function valueInArray(myValue As Variant, myArray As Variant) As Boolean Dim cnt As Long For cnt = LBound(myArray) To UBound(myArray) If LCase(CStr(myValue)) = LCase(CStr(myArray(cnt))) Then valueInArray = True Exit Function End If Next cnt End Function 处,复制并粘贴您的代码。

为什么这个又脏又?主要是因为使用'Do your stuff,因此引用了活动工作表。一旦了解了for-each循环的工作原理,最好阅读How to avoid using Select in Excel VBA-并重写代码。这是有原因的,为什么这是StackOverflow的[vba]中第二受欢迎的话题。

答案 1 :(得分:0)

Sub DataTransfer()
    Dim sht As Worksheet

    Application.ScreenUpdating = False
    For each sht in ThisWorkbook.Worksheets
        If Left(sht.Name, 7) = "payroll" Then DoIt sht
    Next
    Application.ScreenUpdating = True
End Sub


Sub DoIt(copySheet As Worksheet)
    copySheet.Range("A100:AA124").Copy

    Worksheets("CMICIMPORT").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues

    Application.CutCopyMode = False

    MsgBox "Data was copied over to the CMICIMPORT tab successfully", vbInformation, copySheet.Name

    With copySheet.Range("M4").Font
        .Color = -11489280
        .TintAndShade = 0
    End With

End Sub