2014-09-04 3 views
1

Первое сообщение здесь, я приношу свои извинения, если у меня нет каких-либо рекомендаций.Обнаружить, если файл SharePoint открыт

Вот мой вызов: у меня есть файл отслеживания состояния, который сохраняется в SharePoint. Макрос откроет этот статус-трекер, запишет некоторую информацию, сохранит и закроет файл. Я пытаюсь включить некоторый код, чтобы определить, будет ли другой пользователь открывать этот файл статуса, иначе макрос взорвется, когда он увидит, что он не может сохранить изменения. Я знаю, что это не очень элегантная система, но сейчас это будет сделано!

Приведенный ниже код работает при обнаружении открытия файла, но только для локальных файлов (например, для диска C: \). Я не могу заставить его работать для файлов, сохраненных в SharePoint. Я знаю, что мой путь к файлу SharePoint верен, я могу открыть файл, используя операцию «Workbooks.Open». Когда я пытаюсь запустить код для файла SharePoint, он всегда возвращает, что файл НЕ открыт другим пользователем, даже если он есть.

Я бы предпочел не использовать функцию «Отказано» SharePoint и отключить ее. Моя команда не очень добросовестна в проверке вещей.

Большое спасибо!

'**********Function to check if workbook is open********** 
Function IsWorkBookOpen(strFileName As String) 

    On Error Resume Next 
    ' If the file is already opened by another process, 
    ' and the specified type of access is not allowed, 
    ' the Open operation fails and an error occurs. 
    Open strFileName For Binary Access Read Write Lock Read Write As #1 
    Close #1 

    'If no error, file is not open. 
    If Err.Number = 0 Then 
     IsWorkBookOpen = False 
     End If 

    'Error #70 is another user has the file open in edit mode. 
    If Err.Number = 70 Then 
     IsWorkBookOpen = True 
     End If 

    'Error #75 is another user has the file open in read only mode. 
    If Err.Number = 75 Then 
     IsWorkBookOpen = False 
     End If 

End Function 

'**********Running the actual code********** 

Sub Button1_Click() 

'Go into Status Sheet if it's not open. Otherwise skip it. 
If IsWorkBookOpen("\\source.yadda.com\Top_Secret_File_Path\BCR Status Sheet.xlsm") Then 
    MsgBox ("'BCR Status Sheet.xlsm' is open.") 
    Else: MsgBox ("Open it up, do a bunch of stuff.") 
End If 

Workbooks.Open ("\\source.yadda.com\Top_Secret_File_Path\BCR Status Sheet.xlsm") 

MsgBox ("Cruzin' along with rest of macro.") 

End Sub 
+0

Любые идеи люди? Что я могу прояснить? –

+0

http://stackoverflow.com/questions/9373082/detect-whether-excel-workbook-is-already-open – R3uK

ответ

-1

У меня была такая же проблема сегодня, и я решил это, как указано ниже.

Файл в SharePoint: когда кто-то открывает этот файл, заставьте его автоматически открыть другой файл в том месте, где вы можете проверить, открыт ли он.

кода отрезал от моей основной программы

'path to file on SharePoint 
pathDatabank = "http://...sharepoint/sites/.... .xlsm" 

'path to my temp file (this file is opened by my file on SharePoint) 
pathTempfile = "\\ location you can check the file\....\temp.xlsx" 

'check if the temp file is open - with your function 
If IsWorkBookOpen(pathTempfile) Then  
    ' Display a message stating the file is in use. 
    MsgBox "Data bank is in use by an other user."   
    Exit Sub   
End If` 

'before I close and save my file on SharePoint, I close the temp file 
Workbooks("temp.xlsx").Close SaveChanges:=False 

код в моем файле на SharePoint, чтобы открыть временный файл - ThisWorkbook

Private Sub Workbook_Open() 
    Workbooks.Open ("path to your temp file ... \temp.xlsx") 
    ThisWorkbook.Activate 
End Sub 

Private Sub Workbook_BeforeClose(Cancel As Boolean) 
    On Error Resume Next 'because I closed the file in my main programme 
    Workbooks("temp.xlsx").Close SaveChanges:=False 
End Sub 
0

после борьбы с этой проблемой более 8 часов на работе, я понял, быстрое и грязное решение. Это не самый лучший, но после многих исследований до сих пор единственно подходящим. Вот мой код:

«Detect, если файл SharePoint открыт другим пользователем, если да открыть файл, если не закрыть его»

Sub accessWorkbook() 
    Dim url As String 
    url = "mySharePointURL" 

    MsgBox workbookOpen(url) 
End Sub 


Function workbookOpen(url As String) As Boolean 
    'return false if file is not locked by another user 
    workbookOpen = False 


'open the workbook in read.only mode, so does no message is displyed when the file is use 
Set wb = Workbooks.Open(url, False, True) 
'change file access to ReadWrite without notifying if the file is locked by another user 
On Error Resume Next 
wb.ChangeFileAccess xlReadWrite, False, False 

'if the file is locked, this will return "true" 
workbookOpen = wb.ReadOnly 

'if the file is locked, it wil lbe closed without no changes 
If read.only = True Then 
    wb.Close 
End If 

End Function 
+0

Я получаю ошибки автоматизации, а не доступ к изменениям, но когда я делаю wf.ReadOnly, на самом деле, любой доступ к объекту wb дает мне ошибку автоматизации. (excel 2013). –

Смежные вопросы