OneNoteをVBAでいじる - ページ本文の書き換え

簡単に文字だけを書き換える場合

Public Sub PageRewrite2Test()
    Call UpdatePage2(GetPageID("あなたのNotBook名", "書き換え用ページ"), "このページを書き換えました")
End Sub

下図のように書き換わったと思います。

HTMLの書式を使用してみる

Public Sub PageRewrite3Test()
    Call UpdatePage2(GetPageID("MyJob", "書き換え用ページ"), _
        "<b>書き換え太文字</b>" & _
        "")
End Sub

こんな感じになると思います。

OneNoteをVBAでいじる - 本文を書き換える - サブルーチン

まず、共通のサブルーチンを標準モジュールに貼り付けてください。
OneNoteには、「書き換え用ページ」を作成し、何かの本文を入力してください。
何かを入れないと、書き換える場所が判断できず、エラーとなります。
下図のようなページにしてください。

Public Sub UpdatePage2(ByVal id As String, ByVal Body As String)
    Dim oneNote As oneNote.Application2
    Dim outXML As String
    Dim lBuf As Long
    Dim cdataStartPos As Long
    Dim cdataEndPos As Long
    Dim headder As String
    Dim footer As String
    
    If id = "" Then
        Exit Sub
    End If
    
    Set oneNote = New oneNote.Application2
    oneNote.GetPageContent id, outXML, piAll, xsCurrent
    
    '本文の開始位置を取得
    cdataStartPos = InStr(outXML, "<one:Outline")
    '本文内のCDATAセクション位置を取得
    cdataStartPos = InStr(cdataStartPos + 1, outXML, "<![CDATA[")
    cdataEndPos = cdataStartPos + 1
    Do
        '本文内のCDATAセクションの終わりの位置を取得
        lBuf = InStr(cdataEndPos + 1, outXML, "]]>")
        If lBuf > 0 Then
            cdataEndPos = lBuf
        Else
            Exit Do
        End If
    Loop
    
    '本文以前のxmlをheadderとして取得
    headder = Left(outXML, cdataStartPos + 8)
    '本文以後のxmlをfooterとして取得
    footer = Right(outXML, Len(outXML) - cdataEndPos + 1)
    
    'headderと書き換える本文とfooterで、今のページを更新
    oneNote.UpdatePageContent headder & Body & footer
End Sub

OneNoteをVBAでいじる - ページxmlの独自解析

下に抽出したxmlを掲載します。
[ノートシール]
自分は良く、タイトルにノートシールを貼ります。見た目ですね・・・。

こんな感じでノートシールは設定しています。
そして、xml内を確認すると、3行目に

のタグがあります。このタグ内のtypeがノートシールの番号、nameが自分が設定した名称だと推測できます。

[自分の入力した情報]
<![CDATA[ から ]]>内に入っています。これはxmlのCDATAセクションです。

[本文]
本文という言い方が正しいか不明ですが、内に入っています。
ですから本文をVBAで書き換えるためには、内のCDATAセクションを書き換えれば良いのです。さらにCDATA内にはHTMLのタグの一部が使用できますので、書式を変更することができます。

<?xml version="1.0"?>
<one:Page xmlns:one="http://schemas.microsoft.com/office/onenote/2013/onenote" ID="{123E4EFF-5678-901C-2345-67B89012345F}{6}{E78901234567890123456789012345678901234567890}" name="*添付ファイル" dateTime="2017-08-10T07:12:01.000Z" lastModifiedTime="2017-08-13T05:22:22.000Z" pageLevel="1" isCurrentlyViewed="true" selected="partial" lang="ja">
	<one:TagDef index="0" type="2" symbol="107" fontColor="automatic" highlightColor="none" name="Mail"/>
	<one:QuickStyleDef index="0" name="PageTitle" fontColor="automatic" highlightColor="automatic" font="游ゴシック" fontSize="20.0" spaceBefore="0.0" spaceAfter="0.0"/>
	<one:QuickStyleDef index="1" name="p" fontColor="automatic" highlightColor="automatic" font="游ゴシック" fontSize="11.0" spaceBefore="0.0" spaceAfter="0.0"/>
	<one:PageSettings RTL="false" color="automatic">
		<one:PageSize>
			<one:Automatic/>
		</one:PageSize>
		<one:RuleLines visible="false"/>
	</one:PageSettings>
	<one:Title showDate="false" showTime="false" selected="partial" lang="ja">
		<one:OE author="User U" authorInitials="UU" authorResolutionID="&lt;resolutionId provider=&quot;Windows Live&quot; hash=&quot;xxxxxxxxxxxxxxxxxxxxxxx=&quot;&gt;&lt;localId cid=&quot;xxxxxxxxxxxxxxxx&quot;/&gt;&lt;/resolutionId&gt;" lastModifiedBy="User U" lastModifiedByInitials="UU" lastModifiedByResolutionID="&lt;resolutionId provider=&quot;Windows Live&quot; hash=&quot;xxxxxxxxxxxxxxxxxxxxxx==&quot;&gt;&lt;localId cid=&quot;xxxxxxxxxxxxxxxxx&quot;/&gt;&lt;/resolutionId&gt;" creationTime="2017-08-13T05:17:12.000Z" lastModifiedTime="2017-08-13T05:17:12.000Z" objectID="{xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}{xx}{B0}" alignment="left" quickStyleIndex="0" selected="partial">
			<one:Tag index="0" completed="true" disabled="false" creationDate="2017-08-13T05:16:33.000Z" completionDate="2017-08-13T05:16:33.000Z"/>
			<one:T selected="all">
				<![CDATA[
					<span lang=en-US>
						*
					</span>
					<span lang=ja>
						添付ファイル
					</span>
				]]>
			</one:T>
		</one:OE>
	</one:Title>
	<one:Outline author="User U" authorInitials="UU" lastModifiedBy="User U" lastModifiedByInitials="UU" lastModifiedTime="2017-08-13T05:16:46.000Z" objectID="{xxxxxxxxxxxxxxxxxx-xxxx-xxxxxxxxxxxxx}{xx}{B0}">
		<one:Position x="36.0" y="68.4000015258789" z="0"/>
		<one:Size width="105.75" height="101.6111755371094"/>
		<one:Indents>
			<one:Indent level="0" indent="1.05364627395842E-30"/>
		</one:Indents>
		<one:OEChildren>
			<one:OE authorResolutionID="&lt;resolutionId provider=&quot;Windows Live&quot; hash=&quot;xxxxxxxxxxxxxxxxxxxxxxxx==&quot;&gt;&lt;localId cid=&quot;xxxxxxxxxxxxxxxx&quot;/&gt;&lt;/resolutionId&gt;" lastModifiedByResolutionID="&lt;resolutionId provider=&quot;Windows Live&quot; hash=&quot;xxxxxxxxxxxxxxxxxxxxxxxx==&quot;&gt;&lt;localId cid=&quot;xxxxxxxxxxxxxxxx&quot;/&gt;&lt;/resolutionId&gt;" creationTime="2017-08-10T07:12:42.000Z" lastModifiedTime="2017-08-10T07:12:44.000Z" objectID="{xxxxxxxxxxxxxxxxxx-xxxx-xxxxxxxxxxxxx}{14}{B0}" alignment="left" quickStyleIndex="1">
				<one:T>
					<![CDATA[これはテスト]]>
				</one:T>
			</one:OE>
			<one:OE authorResolutionID="&lt;resolutionId provider=&quot;Windows Live&quot; hash=&quot;xxxxxxxxxxxxxxxxxxxxxxxx==&quot;&gt;&lt;localId cid=&quot;xxxxxxxxxxxxxxxx&quot;/&gt;&lt;/resolutionId&gt;" lastModifiedByResolutionID="&lt;resolutionId provider=&quot;Windows Live&quot; hash=&quot;xxxxxxxxxxxxxxxxxxxxxxxx==&quot;&gt;&lt;localId cid=&quot;xxxxxxxxxxxxxxxx&quot;/&gt;&lt;/resolutionId&gt;" creationTime="2017-03-09T00:18:44.000Z" lastModifiedTime="2017-08-13T05:16:41.000Z" objectID="{xxxxxxxxxxxxxxxxxx-xxxx-xxxxxxxxxxxxx}{23}{B0}" alignment="left">
				<one:InsertedFile pathCache="C:\Users\user\AppData\Local\Microsoft\OneNote\16.0\cache\00001AL8.bin" pathSource="C:\Temp\OneNoteAttachments\エクセル1.xlsx" preferredName="エクセル1.xlsx"/>
			</one:OE>
			<one:OE authorResolutionID="&lt;resolutionId provider=&quot;Windows Live&quot; hash=&quot;xxxxxxxxxxxxxxxxxxxxxxxx==&quot;&gt;&lt;localId cid=&quot;xxxxxxxxxxxxxxxx&quot;/&gt;&lt;/resolutionId&gt;" lastModifiedByResolutionID="&lt;resolutionId provider=&quot;Windows Live&quot; hash=&quot;xxxxxxxxxxxxxxxxxxxxxxxx==&quot;&gt;&lt;localId cid=&quot;xxxxxxxxxxxxxxxx&quot;/&gt;&lt;/resolutionId&gt;" creationTime="2017-03-08T04:52:45.000Z" lastModifiedTime="2017-08-10T07:12:33.000Z" objectID="{xxxxxxxxxxxxxxxxxx-xxxx-xxxxxxxxxxxxx}{46}{B0}" alignment="left" quickStyleIndex="1" lang="en-US">
				<one:T>
					<![CDATA[2017/3/8]]>
				</one:T>
			</one:OE>
		</one:OEChildren>
	</one:Outline>
</one:Page>

OneNoteをVBAでいじる - ページxmlの独自解析 - ページ内容の抽出(xml形式)

これは、自分が独自で解析したものですので、正しくない場合があります。色々と探しているのですが、見つけ方が悪いのか、VBAxml形式でページデータを取得した場合の、タグの意味が見つかりません。

下記のコードを実行すると、tempフォルダに 年_月_日_時_分.txt ファイルが作成されます。これは、OneNote内のページを表現しているxml形式のデータとなります。(多分)

Public Sub SavePageContents()
    Dim oneNote As oneNote.Application2
    Dim outXML As String
    Dim objFso As Object
    Dim objFile As Object
    Dim szBuf As String
    Dim szFileName As String
    
    Dim pageID As String
    pageID = "GetPageIDで取得した、あなたのページID"
    
    Set oneNote = New oneNote.Application2
    oneNote.GetPageContent pageID, outXML, piAll, xsCurrent
    
    szFileName = TempFolder & "\" & Format(Now(), "yyyy_mm_dd_hh_nn") & ".txt"

    Set objFso = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFso.OpenTextFile(szFileName, FOR_APPENDING, True, UNICODE)
    objFile.WriteLine outXML
    objFile.Close
    Set objFile = Nothing
    Set objFso = Nothing
End Sub

OneNoteをVBAでいじる - ページの添付ファイル情報を取得する

まずは、標準モジュールの先頭に下記のコードを貼り付けてください。

Public Type AttachedFileInfoType
    pathCache As String
    preferredName As String
End Type

ユーザ定義型で、添付ファイル情報を取得します。
pathCacheは、実ファイルが保存されている場所、preferredNameは、実ファイル名となります。

次に、標準モジュールに下記のコードを貼り付けてください。

Public Function GetAttachedFileInfo(ByVal pageID As String) As AttachedFileInfoType()
    Dim result() As AttachedFileInfoType
    Dim oneNote As oneNote.Application2
    Dim doc As Object
    Dim nodes As MSXML2.IXMLDOMNodeList
    Dim node As MSXML2.IXMLDOMNode
    Dim outXML As String
    Dim count As Integer
    
    If pageID = "" Then
        Exit Function
    End If
    
    Set oneNote = New oneNote.Application2
    oneNote.GetPageContent pageID, outXML, piAll, xsCurrent
    
    Set doc = CreateObject("Msxml2.DOMDocument")
    Call doc.loadXML(outXML)
    Set nodes = doc.DocumentElement.SelectNodes("//one:InsertedFile")
    
    count = -1
    For Each node In nodes
        count = count + 1
        ReDim Preserve result(count) As AttachedFileInfoType
        result(count).pathCache = node.Attributes.getNamedItem("pathCache").nodeValue
        result(count).preferredName = node.Attributes.getNamedItem("preferredName").nodeValue
    Next
    
    GetAttachedFileInfo = result
End Function

このファンクションをテストするコードを貼り付けてください

Public Sub gafiTest()
    Dim result() As AttachedFileInfoType
    Dim i As Integer
    
    result = GetAttachedFileInfo(GetID("ページ名"))
    For i = 0 To UBound(result)
        Debug.Print i & ":実ファイル名[" & result(i).preferredName & "]は" & result(i).pathCache & "に保存されています"
    Next
End Sub

このルーチンを実行すると
0:実ファイル名[エクセル1.xlsx]はC:\Users\user\AppData\Local\Microsoft\OneNote\16.0\cache\0000153G.binに保存されています
1:実ファイル名[エクセル2.xlsm]はC:\Users\user\AppData\Local\Microsoft\OneNote\16.0\cache\00001540.binに保存されています
のように添付ファイル情報が出力されます。

OneNoteをVBAでいじる - ページのIDを取得する

下記のコードを標準モジュールに貼り付けてください。

Public Function GetPageID(ByVal noteBookName As String, ByVal pageName As String) As String
    Dim oneNote As oneNote.Application2
    Dim oneNotePagesXml As String
    Dim nodes As MSXML2.IXMLDOMNodeList
    Dim node As MSXML2.IXMLDOMNode
    Dim doc As Object

    Set oneNote = New oneNote.Application2
    oneNote.GetHierarchy GetNoteBookID(noteBookName), hsPages, oneNotePagesXml
    Set doc = CreateObject("Msxml2.DOMDocument")
    doc.loadXML (oneNotePagesXml)
    
    Set nodes = doc.DocumentElement.SelectNodes("//one:Page")
    For Each node In nodes
        If node.Attributes.getNamedItem("name").Text = pageName Then
            If NotParentName(pageName) = False Then
                GetPageID = node.Attributes.getNamedItem("ID").Text
                Exit Function
            End If
        End If
    Next
End Function

イミディエイトウィンドウで、
? GetPageID("あなたのノートブック名","その中のページ名") [Return]で
{12344EFF-4567-8901-2345-56B789012E1F}{1}{E1234567890123456789012345678901234567891234}
のような形式でIDが取得できます。