简体   繁体   English

启用编辑VBA

[英]Enable editing vba

I am working in Excel 2016. I currently created a macro that will loop through all open workbooks and grab the data in them if they start with the word "report". 我正在使用Excel2016。当前我创建了一个宏,该宏将循环所有打开的工作簿,如果它们以“ report”开头,则将捕获其中的数据。 The issue I am trying to solve now is how to enable editing. 我现在要解决的问题是如何启用编辑。 If the users enable editing after downloading all reports to be combined there is no issue with the macro. 如果用户在下载所有要合并的报告后启用编辑,则宏没有问题。 They run into issues with the macro not grabbing the data if they missed that button. 如果他们错过了该按钮,就会遇到宏无法获取数据的问题。

While they are not working with that many workbooks, I am trying to make it easier for them. 尽管他们没有使用那么多的工作簿,但我正在尝试使他们更轻松。 The code that I have posted will do the first 3 workbooks and then continue looping through the remaining 5 but will not "Enable Edit". 我发布的代码将执行前3个工作簿,然后继续循环浏览其余5个工作簿,但不会“启用编辑”。

 Sub EnableEdit()

 Dim bk As Workbook
 Dim w As Long, wCount As Long

 wCount = Application.ProtectedViewWindows.Count
 Set wsh = ThisWorkbook.Worksheets("Data")

 On Error Resume Next
    If wCount > 0 Then
        For w = 1 To wCount
            Application.ProtectedViewWindows(w).Activate
            Application.ProtectedViewWindows(w).Edit

            If Left(ActiveWorkbook.Name, 6) = "report" Then
                ActiveWorkbook.Worksheets(1).Range("A1:Z1").Copy _
                    Destination:=wsh.Range("A1")
                nrow = wsh.Cells(Rows.Count, 1).End(xlUp).Row + 1
                ActiveWorkbook.Worksheets(1).Range("A2:Z500").Copy _
                    Destination:=wsh.Range("A" & nrow)
                ActiveWorkbook.Close
            End If
        Next w
    End If
 On Error GoTo 0

 End Sub

Application.ProtectedViewWindows appears to be a collection of all the protected-view windows. Application.ProtectedViewWindows似乎是所有受保护视图窗口的集合。 As soon as you execute the .Edit method on one of those protected-view windows it is no longer in protected-view mode and is therefore removed from the collection. 在这些受保护视图窗口之一上执行.Edit方法后,该方法不再处于受保护视图模式,因此将从集合中删除。

This means that when you Edit the first member of the collection (when w is 1 ), what was the second member now becomes the first member, what was the third member now becomes the second, etc. And then on the next iteration of your loop (when w is 2 ) your code is therefore looking at the original third member, having completely ignored looking at the original second member. 这意味着,当您Edit集合的第一个成员时(当w1 ),第二个成员现在变成了第一个成员,第三个成员现在变成了第二个成员,依此类推。然后在您的下一次迭代中循环(当w2 )因此,您的代码将查看原始的第三个成员,而完全忽略了查看原始的第二个成员。

The easiest way to fix the issue is to loop through the array in reverse order, ie use: 解决此问题的最简单方法是以相反的顺序遍历数组,即使用:

For w = wCount To 1 Step -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM