我在一个Excel工作簿中有一些VBA脚本,它有三个子节点,每个子节点都从第二个工作簿中读取。每个子使用以下算法(简化为提取与第二本书的交互):
Public Sub EditRemote()
Dim remoteDataSheet As Worksheet
Dim source As String 'Source worksheet name
Dim target As String 'Target worksheet name
Dim path As String
Dim wkbName As String
source = "CountData"
path = ThisWorkbook.Worksheets("Parameters").Range("B2").Value
wkbName = ThisWorkbook.Worksheets("Parameters").Range("A2").Value
target = "CountData"
Application.EnableCancelKey = xlDisabled
Set localDataSheet = ThisWorkbook.Sheets(source)
If Not WorkbookIsOpen(wkbName) Then
Workbooks.Open (path)
End If
Set remoteDataSheet = Workbooks(wkbName).Sheets(source)
remoteDataSheet.Cells(1,1) = localDataSheet.Cells(1,1)
remoteDataSheet.Cells(1,2) = localDataSheet.Cells(1,2)
Workbooks(wkbName).Close SaveChanges:=True
End Sub
Function WorkbookIsOpen(targetWorkbook As String) As Boolean
Dim testBook As Workbook
On Error Resume Next
Set testBook = Workbooks(targetWorkbook)
If Err.Number = 0 Then
WorkbookIsOpen = True
Else:
WorkbookIsOpen = False
End If
End Function
此工作簿中还有一个数据透视表,它通过外部数据连接从第二个文件中提取数据。困扰我的问题是,似乎不是最初但是在几次操作之后,这些子设备会停止正确编辑,而是打开第二个工作簿的只读副本。当我尝试手动打开第二个工作簿时,我收到一条消息,指出该文件已经打开并被锁定以进行编辑。现在,这两个文件都是我的计算机的本地文件,并且其他任何人都无法打开。我错过了什么,以确保我可以使代码按预期工作?
答案 0 :(得分:0)
我对您的代码进行了一些修改,运行了几次,但没有收到“只读”消息。
在您的代码中,缺少声明localDataSheet
的行,添加了Dim localDataSheet As Worksheet
,并为远程工作簿添加了Dim remoteWb As Workbook
。
(未修改您的Funtion WorkbookIsOpen
代码。)
Sub EditRemote Code
Option Explicit
Public Sub EditRemote()
Dim remoteDataSheet As Worksheet
Dim localDataSheet As Worksheet
Dim source As String 'Source worksheet name
Dim target As String 'Target worksheet name
Dim path As String
Dim wkbName As String
Dim remoteWb As Workbook
source = "CountData"
path = ThisWorkbook.Worksheets("Parameters").Range("B2").Value
wkbName = ThisWorkbook.Worksheets("Parameters").Range("A2").Value
target = "CountData"
Application.EnableCancelKey = xlDisabled
Set localDataSheet = ThisWorkbook.Sheets(source)
' check if workbbok already open
If Not WorkbookIsOpen(wkbName) Then
Set remoteWb = Workbooks.Open(path)
Else
Set remoteWb = Workbooks(wkbName) ' workbook is open >> set remoteWb accordingly
End If
Set remoteDataSheet = remoteWb.Sheets(source)
remoteDataSheet.Cells(1, 1) = localDataSheet.Cells(1, 1)
remoteDataSheet.Cells(1, 2) = localDataSheet.Cells(1, 2)
Workbooks(wkbName).Close SaveChanges:=True
End Sub
只是为了验证Excel“参数”表中的数据,下面的屏幕截图显示了我用于测试的数据。
单元格A2包含“清洁”工作簿名称。
单元格B2包含workbbok“完整”名称 - 路径+“干净”工作簿名称。
答案 1 :(得分:0)
经过一些进一步的测试来诊断问题之后,我发现VBA代码没有任何问题,而是远程工作簿的外部数据连接是每次刷新使用的数据透视表中的数据时都锁定该工作簿外部数据连接作为其来源。完成刷新后,它不会解锁文件,并且在我使用数据透视表关闭工作簿之前会使文件保持锁定状态。现在我只需要解决这个问题。