Creating new Section in onenote using VBA - vba

Hi I have searched through the internet looking for examples of creating a new onenote section and I can't find the right example for me to understand. The closest I can get to is using .OpenHierarchy function but I'm still very new to it and I couldn't get the parameters right.
I'm currently working on an OCR marco for multiple PDF file. Everything is working fine till I realise that I'm creating huge waste files on my computer.
Here's the code I used to delete all the pages created in the section
Dim oneNote As OneNote14.Application
Dim secDoc As MSXML2.DOMDocument60
Set secDoc = New MSXML2.DOMDocument60
Dim secNodes As MSXML2.IXMLDOMNodeList
Set secNodes = secDoc.DocumentElement.getElementsByTagName("one:Section")
' Get the first section.
Dim secNode As MSXML2.IXMLDOMNode
Set secNode = secNodes(0)
Dim sectionName As String
sectionName = secNode.Attributes.getNamedItem("name").Text
Dim sectionID As String
sectionID = secNode.Attributes.getNamedItem("ID").Text
oneNote.DeleteHierarchy (sectionID)
oneNote.OpenHierarchy
End Sub
Deletehierarchy function deletes the entire section away leaving no section behind but my OCR macro requires at least one section to work.
Thanks for reading and thank you in advance!

oneNote.OpenHierarchy in vba does not allow bracklet and thats the issue that is causing the error.
solution:
oneNote.OpenHierarchy fileName, "", "New Section 1", 3

Related

How to get a container header id to a variable and passed to vba to write a new header?

I have created this script to generate a container that I want to use it to generate containers It works fine but I also need to be able to give the containers a custom header. As you can see I tried to capture the shape id in a variable so I could use the variable to get the shape Id for the container. Nevertheless, I cannot get the shape id or assign one statically I also found out that the container has more than one shape ID. How do I Identify the ID for the header portion. I also need to be able to drop shapes in the container. I followed Microsoft instructions and tried using
vsoContainerShape.ContainerProperties.AddMember vsoShape,
visMemberAddExpandContainer
However that doesn’t work.
Sub Add_Container()
Dim DiagramServices As Integer
DiagramServices = ActiveDocument.DiagramServicesEnabled
ActiveDocument.DiagramServicesEnabled = visServiceVersion140 +
visServiceVersion150
Dim visapp As Visio.Application
Dim vlan30 As Visio.Document
Dim node As Visio.Shape
Dim vlan30id As Integer
Application.Documents.OpenEx(Application.GetBuiltInStencilFile(visBuiltInStencilContainers, visMSUS), visOpenHidden)
Application.Windows.ItemEx("container.vsdm").Activate 'need to activate
Application.ActiveWindow.Page.DropContainer vlan30.Masters.ItemU("Classic"), Nothing
vlan30id = vlan30.ID
Debug.Print vlan30id
Dim v30chars As Visio.Characters
Set v30chars = Application.ActiveWindow.Page.Shapes.ItemFromID(vlan30id).Characters
v30chars.Begin = 0
v30chars.End = 7
v30chars.Text = "Vlan_30"
vlan30.Close
ActiveWindow.DeselectAll
'Restore diagram services
ActiveDocument.DiagramServicesEnabled = DiagramServices
End Sub
I need to be able to get the shape id for the heading of the containers and stored in a variable so I can use the variable for passing the argument in the ItemFromID. Thanks
First things first: your exact question was already answered her: http://visguy.com/vgforum/index.php?topic=6787.0
I packaged the whole code into a function, calling the function will drop a classic container on the page you passed as argument and fill the caption with the passed caption argument. The return value is the dropped Container, bottom function shows how to use the function and add shapes to the container.
'#Folder("ExampleDropContainer")
Option Explicit
Public Function DropContainerWithCaption(pg As Visio.Page, caption As String) As Visio.Shape
Dim vsPg As Visio.Page
Set vsPg = pg
Dim vsStencilName As String
vsStencilName = Application.GetBuiltInStencilFile(visBuiltInStencilContainers, visMSUS)
Dim vsStencil As Visio.Document
Set vsStencil = Application.Documents.OpenEx(vsStencilName, visOpenHidden)
Dim vsMas As Visio.Master
Set vsMas = vsStencil.Masters.ItemU("Classic")
'If you already had the shapes you want to have inside the continer you can replace "Nothing" with them.
Dim droppedContainer As Visio.Shape
'Set droppedContainer = vsPg.DropContainer(vsMas, Nothing)
'Using page.Drop circumvents some issues when a shape already occupies the space where the shape is to be dropped.
Set droppedContainer = vsPg.Drop(vsMas, 0, 0)
droppedContainer.Text = caption
Set DropContainerWithCaption = droppedContainer
End Function
Sub TestExample()
Dim newContainer As Visio.Shape
Set newContainer = DropContainerWithCaption(ActivePage, "Bananas")
'Example on how to add a Shape to the container, someShape is a visio.shape object
'newContainer.ContainerProperties.AddMember someShape
End Sub
You seem to have posted a lot of questions concerning the same or similar problems lately, most of which are quite basic once you get to know VBA. You should read up a bit, especially on the concept of return values of functions. Also be aware that most questions regarding programming in Visio are exactly the same in VBA for Excel, only the interaction with the document/workbook is sometime different. Many answers can be found when searching properly
Some good links are:
How to avoid Select Probably the most read article concerning VBA in Stackoverflow
ExcelMacroMastery Good Resource, a lot on the basics of programming in VBA
Chip Pearson's Website Lots of great and deep information
RubberduckVBA Blog Fantastic resource with many examples on how to bring VBA-Code up to modern standards. He's also active here on SO
The first two links are a must-read IMHO, the other two are great if you want to dive deeper into VBA.

How do I center a paragraph in Word using vb.net?

I am using Visual Studio 2015 and coding in vb.net and importing Microsoft.Office.Interop.Word . I am using the following code to create a one page Word document with only two lines. How can I center, both vertically and horizontally these two lines? Also, is there a way to put both lines, with a line break in between, in one paragraph rather than using two? I am very new to this type of programming so please be specific. Thanks.
Private Sub CreateTitlePage2()
Dim wdApp As Microsoft.Office.Interop.Word.Application = New Microsoft.Office.Interop.Word.Application
Dim wdDoc As Microsoft.Office.Interop.Word.Document = New Microsoft.Office.Interop.Word.Document
Dim wdPara1 As Microsoft.Office.Interop.Word.Paragraph
Dim wdPara2 As Microsoft.Office.Interop.Word.Paragraph
wdDoc.Application.Visible = False
wdPara1 = wdDoc.Content.Paragraphs.Add
wdPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter
wdPara1.Range.Font.Bold = True
wdPara1.Range.Text = "BINDER DOCUMENT"
wdPara1.Range.InsertParagraphAfter()
wdPara2 = wdDoc.Content.Paragraphs.Add
wdPara2.Format.SpaceBefore = WdVerticalAlignment.wdAlignVerticalCenter
wdPara2.Range.Font.Bold = True
wdPara2.Range.Text = "Created: " + formattedDate2
wdPara2.Range.InsertParagraphAfter()
wdDoc.SaveAs(binderNameDoc)
wdDoc.Close()
wdApp.Quit()
End Sub
#Ross: It would help if you'd describe HOW it's "not working". However...
WdVerticalAlignment is not valid applied to a paragraph object, I'm surprised you're not getting a compiler error. See https://msdn.microsoft.com/en-us/library/aa224305(v=office.11).aspx.
If you want to center something vertically on the page then it must be done via the PageSetup object and then it will apply to the entire SECTION. See https://msdn.microsoft.com/en-us/library/office/ff838676.aspx?f=255&MSPPError=-2147217396
If you document is really only the one page, as you say, then you don't need to worry about the SECTION part as the document will have only the one.
RE Line break: Insert ANSI 11 character (vbVerticalTab) for a line break (what you get when pressing Shift+Enter in the Word application).

Text from webpage

I need to get some text from this web page. I want to use the trade feed for my program to analyse the sentiment of the markets.
I used the browser control and the get element command but its not working. The problem is that whenever my browser starts to open the page I get Java scripts errors.
I tried with DOM but seems that i dont quite understand what i need to do :)
Here is the code:
Dim code As String
Using client As New WebClient
code = client.DownloadString("http://openbook.etoro.com/ahanit/#/profile/Trades/")
End Using
Dim htmlDocument As IHTMLDocument2 = New HTMLDocument(code)
htmlDocument.write(htmlDocument)
Dim allElements As IHTMLElementCollection = htmlDocument.body.all
Dim allid As IHTMLElementCollection = allElements.tags("id")
Dim element As IHTMLElement
For Each element In allid
element.title = element.innerText
MsgBox(element.innerText)
Next
Update: So I tried the HTML Agility pack, as suggested in the comments, and I am stuck again on this code
Dim plain As String = String.Empty
Dim htmldoc As New HtmlAgilityPack.HtmlDocument
htmldoc.LoadHtml("http://openbook.etoro.com/ahanit/#/profile/Trades/")
Dim goodnods As HtmlAgilityPack.HtmlNodeCollection = htmldoc.DocumentNode.SelectNodes("THE PROBLEM")
For Each node In goodnods
TextBox1.Text = htmldoc.DocumentNode.InnerText
Next
Any advice what to now?
Ok I think I know what the problem is somehow the div that I need is hidden and its not loaded when I load the web page just the source code. Does someone knows how to load all the hidden divs ??
Here is my new code
Dim doc As New HtmlAgilityPack.HtmlDocument
Dim web As New HtmlWeb
doc = web.Load("http://openbook.etoro.com/ahanit/#/profile/Trades/")
Dim nodes As HtmlNode = doc.GetElementbyId("feed-items")
Dim id As String = nodes.WriteTo()
TextBox1.Text = TextBox1.Text & vbCrLf & id
user1336635,
Welcome to SO! Something you might try is to check out his source code, figure out what javascript function is populating the field you want (using firebug - I assume it's the one that "trades result in profit" next to it), and then embedding that script into a web page that your webbrowser control loads. That's where I'd try to start. I checked his source code and searched for "trades result in profit" and didn't find anything which leads me to believe hunting for the element 'might' not be possible. Just a starting place until someone with more experience with this chimes in!! Best!
-sf

Parse text file and create an excel report

My application is supposed to parse a text file (relatively easy) and create an excel spreadsheet report.
Should I write a stand alone VB.NET application that saves the excel file, or should I use VSTO? I am unsure if there are any differences in terms of ease of development, usability issues, API functions available, etc.
Are there any other programming languages/interfaces/libraries that will allow me to rapidly develop an involved excel spreadsheet? I am talking about things like functions, graphs, etc.
Thank you
You can do this very easily by taking advantage of excel 2007 format (.xlsx)
Here is what I did, you can modify it pretty easily. Im basically taking advantage that the xlsx file is really just a zip file containing xml files.
I created an empty excel file called Empty.xlsx and added it to my application as a resource. (build action embedded resource)
I'm also using a library for standard zip and unzip since that is how you get at the parts of the excel file.
Here is how i take a datatable and create the excel file.. notice that Excel is not actually needed.
Private Function CreateExcelReport(ByVal FilePath As String, ByVal tbl As DataTable) As FileInfo
'Just loading the excel file from the assembly, you could do it from a file also
Dim _assembly As Assembly = Assembly.GetExecutingAssembly
Dim xlStream As New StreamReader(_assembly.GetManifestResourceStream("YourAssembly.Empty.xlsx"))
'Create a new fileinfo that will hold the outputed excel file with the data.
Dim fiRet As New FileInfo(FilePath)
'Im using Ionic Zip Reduced free library to break the slsx file into its subparts
Using z As ZipFile = ZipFile.Read(xlStream.BaseStream)
'Grab Sheet 1 out of the file parts and read it into a string.
Dim myEntry As ZipEntry = z("xl/worksheets/sheet1.xml")
Dim msSheet1 As New MemoryStream
myEntry.Extract(msSheet1)
msSheet1.Position = 0
Dim sr As New StreamReader(msSheet1)
Dim strXMLData As String = sr.ReadToEnd
'Grab the data in the empty sheet and swap out the data that I want
Dim str2 As XElement = CreateSheetData(tbl)
Dim strReplace As String = strXMLData.Replace("<sheetData/>", str2.ToString)
z.UpdateEntry("xl/worksheets/sheet1.xml", strReplace)
'This just rezips the file with the new data it doesnt save to disk
z.Save(fiRet.FullName)
End Using
'Return a Fileinfo class to be saved to disk or DB or streamed to browser
Return fiRet
End Function
Private Function CreateSheetData(ByVal dt As DataTable) As XElement
Dim sheedata As XElement = <sheetData></sheetData>
'Create Header Rows
Dim HeaderRow As New XElement(<row></row>)
For j = 0 To dt.Columns.Count - 1
Dim c As New XElement(<c t="inlineStr"></c>)
Dim _is As New XElement(<is></is>)
Dim v As New XElement(<t></t>)
v.Add(dt.Columns(j).ColumnName)
_is.Add(v)
c.Add(_is)
HeaderRow.Add(c)
Next
sheedata.Add(HeaderRow)
'Create row for each datarow
For Each dr As DataRow In dt.Rows
Dim newrow As New XElement(<row></row>)
For j = 0 To dt.Columns.Count - 1
Dim c As New XElement(<c t="inlineStr"></c>)
Dim _is As New XElement(<is></is>)
Dim v As New XElement(<t></t>)
v.Add(dr(j).ToString)
_is.Add(v)
c.Add(_is)
newrow.Add(c)
Next
sheedata.Add(newrow)
Next
Return sheedata
End Function
As far as in what form you develop this application, it's really up to you. I would base it on what kind of deployment you would like to use.
If you choose to do it outside of excel, then I would look into EPPlus.
For commercial libraries, you should look at Aspose Cells and SpreadsheetGear.
It's been a while since I've used either, but I recall that the Aspose approach is focused on calling into their libraries from code, and does not require Excel, while SpreadsheetGear is somewhat more template-driven.

How to do Mailmerge in Openoffice using Vb.net

Its 5th Question and apart of one I didn't get response from the experts....
Hope this time I will get the helping hand.
I want to do mailmerge in openoffice using Vb.net and I am totally new with openoffice.
I searched on net for some help to understand how to use openoffice with vb.net but all I get is half info.....So can you please help me and give me code for mailmerge in vb.net for openoffice.
Well i have list of workers in DB and there is this facility that if they want to mail to all or some of the workers then they can do it.I have completed this task using Microsoft Office now as a Add in we are providing the facility to perform the same task using Open Office.
What they have to do is just select the List of workers and click on a button and it will automate the mailmerge using the field of those workers data from DB. The Code of mine is as shown below
Public Sub OpenOfficeMail(ByVal StrFilter As String)
Dim oSM ''Root object for accessing OpenOffice from VB
Dim oDesk, oDoc As Object ''First objects from the API
Dim arg(-1) ''Ignore it for the moment !
''Instanciate OOo : this line is mandatory with VB for OOo API
oSM = CreateObject("com.sun.star.ServiceManager")
''Create the first and most important service
oDesk = oSM.createInstance("com.sun.star.frame.Desktop")
''Create a new doc
oDoc = oDesk.loadComponentFromURL("private:factory/swriter", "_blank", 0, arg)
''Close the doc
oDoc.Close(True)
oDoc = Nothing
''Open an existing doc (pay attention to the syntax for first argument)
oDoc = oDesk.loadComponentFromURL("file:///C:\Users\Savan\Documents\1.odt", "_blank", 0, arg)
Dim t_OOo As Type
t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager")
Dim objServiceManager As New Object
objServiceManager = System.Activator.CreateInstance(t_OOo)
Dim oMailMerge As New Object
oMailMerge = t_OOo.InvokeMember("createInstance", Reflection.BindingFlags.InvokeMethod, Nothing, _
objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"}) 'com.sun.star.text.MailMerge"})
oMailMerge.DocumentURL = "file:///C:\Users\Savan\Documents\1.odt"
oMailMerge.DataSourceName = CreateSource(StrFilter)''Function that will return the datasource name which will be a text file's path
oMailMerge.CommandType = 0
oMailMerge.Command = "file:///C:\Mail.txt"
oMailMerge.OutputType = 2
oMailMerge.execute(New [Object]() {})**---->I am getting Error here**
End Sub