vb.net Office365 sharepoint check file open by user - excel

I have the following script to access an excel file from office365 Sharepoint.
dim objApp2 As Excel.Application
dim objBook2 As Excel._Workbook
dim objBooks2 As Excel.Workbooks
dim objSheets2 As Excel.Sheets
dim objSheet2 As Excel._Worksheet
link="sharepointlink"
objApp2 = New Excel.Application()
objBooks2 = objApp2.Workbooks
objBook2 = objBooks2.Open(link, [ReadOnly]:=False)
objSheets2 = objBook2.Worksheets
ws2 = objSheets2("Data")
Dim valoare As Integer
valoare = Int(ws2.Range("a1").Value)
ws2.Range("a1").Value = valoare + 1
objBook2.SaveAs()
objBook2.Close(False)
I have a problem: If someone accesses my link and opens the file, either on Sharepoint or opened locally, I get an error when trying to close the object or save the file.
How can I check if the file is opened by someone when I try to save, or is there another way to access the file?

Welcome to the site. The ReadOnly property should tell you if another person has it open, especially when you said you want it NOT to be. You may ultimately need to switch to a shared workbook, but this should do the trick.
dim objApp2 As Excel.Application
dim objBook2 As Excel._Workbook
dim objBooks2 As Excel.Workbooks
dim objSheets2 As Excel.Sheets
dim objSheet2 As Excel._Worksheet
link="sharepointlink"
If IsFileInUse(link) then
MsgBox "Cannot update Excel file"
Exit Sub 'End
End If
objApp2 = New Excel.Application()
objBooks2 = objApp2.Workbooks
objBook2 = objBooks2.Open(link, [ReadOnly]:=False)
objSheets2 = objBook2.Worksheets
ws2 = objSheets2("Data")
Dim valoare As Integer
valoare = Int(ws2.Range("a1").Value)
ws2.Range("a1").Value = valoare + 1
objBook2.SaveAs()
objBook2.Close(False)
Public Function IsFileInUse(sFile As String) As Boolean
Try
Using f As New IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
End Using
Catch Ex As Exception
Return True
End Try
Return False
End Function

Related

Accessing One Drive files offline in VB .Net

I am working on an application that stores it's files in the Documents folder to easily sync with One Drive. I need to make them available offline, in case of an outage. I have changed the settings so that I have a local copy. When I click directly on the Excel file in File Explorer, the program opens it with no problem. However, when I try to open the file in my application, I get an error stating "No network found..." etc. Is there another way to do this? Thanks in advance.
Public Sub LoadMemberList()
lstMemberList.Clear()
Dim mMember As Members
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim range As Excel.Range
xlApp = New Excel.Application
xlBook = xlApp.Workbooks.Open(CurrentYearPath) '***This is where the exception is thrown.
xlSheet = xlBook.Worksheets("sheet1")
range = xlSheet.UsedRange
Dim rs As Object(,) = CType(range.Value, Object(,))
Dim records As Long = rs.GetUpperBound(0)
If records > 1 Then
For x = 2 To records
mMember.MemberNumber = FormatNumber(rs(x, 1))
mMember.MemberName = rs(x, 4) + " " + rs(x, 3)
lstMemberList.Add(mMember)
Next
End If
xlBook.Close()
xlApp.Quit()
KillExcel()
xlApp = Nothing
xlBook = Nothing
xlSheet = Nothing
range = Nothing
End Sub
Public Function CurrentYearPath() As String
Dim CurrentYear As Integer
CurrentYear = CInt(Format(Now, "yyyy"))
Return My.Computer.FileSystem.SpecialDirectories.MyDocuments + "\DailyBook\Rosters\Membership" + CurrentYear.ToString + ".xlsx"
End Function
Scroll down here
https://learn.microsoft.com/en-us/onedrive/plan-onedrive-enterprise#key-onedrive-features
and you'll find this,
However, if you plan to access a file while disconnected from the internet, you can make the file available offline by right-clicking it, and then selecting Always keep on this device.

How to add multiple sheets to an Excel workbook and save it (infinite loading)

I want to add multiple empty sheets to a existing workbook, the langage is VB.net and the code is launched on a local server
The complete code :
Dim objApp As Excel.Application
Dim objBook As Excel._Workbook
Dim objBooks As Excel.Workbooks
objApp = New Excel.Application()
objApp.Visible = True
objBooks = objApp.Workbooks
objBook = objApp.Workbooks.Open(MyPath)
For i As Integer = 1 To 10
objBook.Sheets.Add()
Next
objBook.Save()
objBook.Close()
objApp.Quit()
When the code is executed, the xls file is saved but no sheets have been added.
And i have infinite loading with my localhost
Thanks for your help.
Your code works fine .....
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Dim objApp As Excel.Application
Dim objBook As Excel._Workbook
Dim objBooks As Excel.Workbooks
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
objApp = New Excel.Application()
objApp.Visible = True
objBooks = objApp.Workbooks
objBook = objApp.Workbooks.Open("\\PC1\1.xlsx")
For i As Integer = 1 To 10
objBook.Sheets.Add()
Next
objBook.Save()
objBook.Close()
objApp.Quit()
End Sub
End Class
Just make the executable and then run it in the mode
Run as administrator
By pressing the right click program and then clicking on Run as administrator

Count lines (max) with values

I would like to count the lines that have values. I tried oSheet.Rows.Count but that doesn't work. Any idea about this?
My code is the following:
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets("Sheet")
oSheet.Range("A" & max).Value = "0000111"
oSheet.Range("B1").Value ="Name"
oBook.SaveAs("C:\New folder\excel\" & datenw & ".xlsx")
oExcel.Quit()
As said in the comments, the following code should get you the count of rows that have values based on your Range:
Dim rowCount As Integer = oSheet.UsedRange.Rows.Count()
There is however a slight issue with your code I believe. This probably won't work:
oSheet = oBook.Worksheets("Sheet")
The reason it won't, is because "Sheet" doesn't exist on a new Workbook. "Sheet1" does, so this needs to be changed to:
oSheet = oBook.Worksheets("Sheet1")
'or
oSheet = oBook.Worksheets(1) 'remember Excel collections are one based not zero based
Lastly I would look at the way you are closing Excel as oExcel.Quit() is probably leaving an instance of Excel running. Have a look at this answer which links to Siddharth Rout's bit of code:
Private Sub ReleaseObject(ByVal obj As Object)
Try
Dim intRel As Integer = 0
Do
intRel = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
Loop While intRel > 0
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
You also to make sure you release in the right order and release everything. This is usually in backwards order:
ReleaseObject(oSheet)
oBook.Close()
ReleaseObject(oBook)
oExcel.Quit()
ReleaseObject(oExcel)
However with all that said I would look at using the Microsoft.Office.Interop.Excel namespace directly rather than declaring objects:
Imports Microsoft.Office.Interop
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim oExcel As New Excel.Application
Dim oWorkbooks As Excel.Workbooks = oExcel.Workbooks
Dim oWorkbook As Excel.Workbook = oWorkbooks.Add()
Dim oSheets As Excel.Sheets = CType(oWorkbook.Sheets, Excel.Sheets)
Dim oWorksheet As Excel.Worksheet = CType(oSheets(1), Excel.Worksheet)
Dim oARange As Excel.Range = oWorksheet.Range("A" & max.ToString()) 'Not sure what max is but I took the assumption it's an Integer
oARange.Value = "0000111"
Dim oBRange As Excel.Range = oWorksheet.Range("B1")
oBRange.Value = "Name"
Dim oUsedRange As Excel.Range = oWorksheet.UsedRange()
Dim rowCount As Integer = oUsedRange.Rows.Count()
oWorkbook.SaveAs("C:\Test.xlsx")
ReleaseObject(oUsedRange)
ReleaseObject(oBRange)
ReleaseObject(oARange)
ReleaseObject(oWorksheet)
ReleaseObject(oSheets)
oWorkbook.Close()
ReleaseObject(oWorkbook)
ReleaseObject(oWorkbooks)
oExcel.Quit()
ReleaseObject(oExcel)
End Sub
Private Sub ReleaseObject(ByVal obj As Object)
Try
Dim intRel As Integer = 0
Do
intRel = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
Loop While intRel > 0
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
I would also then look at turning Option Strict On:
Restricts implicit data type conversions to only widening conversions, disallows late binding, and disallows implicit typing that results in an Object type.
Define a row variable as Long, then start a loop which will end when it finds a blank value in column A:
Dim lRow as Long = 1
Do until oSheet.Range("A" & lRow).Value=""
' increment the loop variable
lRow+=1
Loop
' display the result in a message block
MsgBox(lRow-1)

Disable excel save changes prompt

I have tried all the ways I normally do this and what I can find searching. oxl.DisplayAlerts = False is not working. I still get asked if I want to save changes.
I am essentially trying to use the excel sheet as a template. The full script exports to pdf, but this is enough to re-create the problem. BTW I tried saving it as a xltx file (template) and still get the save promt.
Dim oxl As New Excel.Application
Dim apppath2 As String = My.Application.Info.DirectoryPath.ToString
Dim mywb As Excel.Workbook = oxl.Workbooks.Open(Filename:=apppath2 & "\fuse template.xlsx", [ReadOnly]:=True)
oxl.Visible = False
Dim mysheet As Excel.Worksheet = mywb.Sheets(1)
mysheet.Cells(10, 5) = l_region.Text
mysheet.Cells(11, 5) = comb_emc_name.Text
oxl.DisplayAlerts = False
mywb.Close(False)
mysheet = Nothing
mywb = Nothing
oxl = Nothing
GC.Collect()
I was missing mywb.Saved = True. I have never had to do that before.

Excel 2010 - 'The image part with relationship ID rId1 was not found in the file.' When copying sheets of a workbook into another workbook

I have a source excel workbook (XLSM format) that has sheets containing images. These sheets are programatically copied into another(target) workbook (XLSM) using VB.NET late binding. After all the copy is done i save the workbook and launch it. In the opened excel workbook I see the error message 'The image part with relationship ID rId1 was not found in the file' at all places where the images are placed.
All the operations are done in the client machine no server side code available.
Interestingly this issue doesn't occur in Excel 2013 and it displays the images properly issue is observed only in 2010 and 2007. Is this a know bug in Excel 2010 and 2007 if yes can any one provide me the official link to the ticket so that i can track the issue and get the Hot fix once it is available.
Dim SourceExcelWorkbook As Excel.Workbook = Nothing
Dim TargetExcelWorkbook As Excel.Workbook = Nothing
Dim TargetExcelSheets As Excel.Sheets = Nothing
Dim SourceExcelSheets As Excel.Sheets = Nothing
Dim CopyWorkSheet As Excel.Worksheet = Nothing
Dim XLApp As New Excel.Application
XLApp.Visible = False
XLApp.DisplayAlerts = False
XLApp.ScreenUpdating = False
Dim pobjExcelWorkbooks As Excel.Workbooks = XLApp.Workbooks
SourceExcelWorkbook = pobjExcelWorkbooks.Open("source file path")
TargetExcelWorkbook = pobjExcelWorkbooks.Open("target file path")
TargetExcelSheets = TargetExcelWorkbook.Worksheets
SourceExcelSheets = SourceExcelWorkbook.Worksheets
Dim OriginalSheetCount As Integer = TargetExcelSheets.Count
Dim SheetCount As Integer = OriginalSheetCount
Dim SheetsToBeCopiedCount As Integer = SourceExcelSheets.Count
While SheetsToBeCopiedCount > 0
Dim lobjAfterSheet As Object = TargetExcelSheets.Item(SheetCount)
CopyWorkSheet = SourceExcelSheets.Item(1)
CopyWorkSheet.Move(After:=lobjAfterSheet)
SheetCount = SheetCount + 1
TargetExcelWorkbook.Save()
SheetsToBeCopiedCount = SheetsToBeCopiedCount - 1
End While
TargetExcelWorkbook.Save()

Resources