已在使用的控制变量 - 简单的 VBA 脚本

Control variable already in use - simple VBA script

提问人:poppyaf 提问时间:7/30/2020 最后编辑:Chronocidalpoppyaf 更新时间:7/30/2020 访问量:324

问:

为此使用控制变量,我猜是因为“ws”,有人可以帮助解决吗?谢谢

Sub CreateNewWBS()
    Dim wbThis As Workbook
    Dim wbNew As Workbook
    Dim ws As Worksheet
    Dim strFilename As String
    Set wbThis = ThisWorkbook
    For Each ws In wbThis.Worksheets
        strFilename = wbThis.Path & "/" & ws.Name
        ws.Copy
        Set wbNew = ActiveWorkbook
        For Each ws In wbNew.Worksheets
            ws.Cells.Copy
            ws.Cells.PasteSpecial xlPasteValues

        wbNew.SaveAs strFilename
        wbNew.Close
    Next ws
End Sub
Excel VBA

评论

3赞 BigBen 7/30/2020
Dim ws2 as Worksheet并用它来代替?此外,您还缺少一个 .Next
2赞 Chronocidal 7/30/2020
我不明白目的吗?当然,它只是 ,在宏执行期间不会(并且从字面上看不会)改变?wbThisThisWorkbook
0赞 poppyaf 7/30/2020
@Chronocidal我想只是为了区分 wbNew。该代码在没有“复制粘贴值”部分的情况下工作。
0赞 poppyaf 7/30/2020
@BigBen 我能否获得如何在“复制粘贴值”部分之前“设置”wb2 的指导?
1赞 BigBen 7/30/2020
我求婚了,你什么都不做。, , .ws2SetFor Each ws2 in wbNew.Worksheetsws2.Cells.Copyws2.Cells.PasteSpecial xlPasteValues

答:

2赞 poppyaf 7/30/2020 #1

使用 ws2 并修复了 Next 语句,现在有效:

Sub CreateNewWBS()
Dim wbThis As Workbook
Dim wbNew As Workbook
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim strFilename As String
Set wbThis = ThisWorkbook
For Each ws In wbThis.Worksheets
    strFilename = wbThis.Path & "/" & ws.Name
    ws.Copy
    Set wbNew = ActiveWorkbook
        For Each ws2 In wbNew.Worksheets
            ws2.Cells.Copy
            ws2.Cells.PasteSpecial xlPasteValues
        Next
    wbNew.SaveAs strFilename
    wbNew.Close
Next ws
End Sub
1赞 Chronocidal 7/30/2020 #2

下面是代码的简化版本:

Sub CreateNewWBs()
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        ws.Copy
        With ActiveWorkbook
            .Worksheets(1).UsedRange.Value = .Worksheets(1).UsedRange.Value
            .SaveAs ThisWorkbook.Path & "/" & ws.Name
            .Close
        End With
    Next ws
End Sub

我已经删除了第二个循环,它给您带来了问题(既因为您没有 ,也因为您试图重用现有变量),因为该循环仅包含 1 个工作表,替换为 ,并交换了 ,以避免需要剪贴板。ForForNextwbNewwbThisThisWorksheet.Copy:.PasteSpecial.Value=.Value