はじめに
PDFファイルテキストをエクセルシートに書き出しを行う
プロシジャーの説明
指定のPDFファイルのテキストデータをエクセルシートへ書き出します。
PDFファイルをMicrosoft Wordで開き、その内容をExcelに転記するVBAマクロです。「Adobe Acrobat SDK」や「iTextSharp」など無しで動作します。
サンプル1
Sub PDFToExcelImproved999()
Dim wordApp As Object
Dim wordDoc As Object
Dim pdfPath As String
Dim wordText As String
Dim textLines As Variant
Dim i As Long
' PDFファイルのパスを指定
pdfPath = "C:\ALLlib\エクセルマクロ\test\AAA.pdf"
' Wordアプリケーションを作成
On Error Resume Next
Set wordApp = CreateObject("Word.Application")
If wordApp Is Nothing Then
MsgBox "Microsoft Wordが見つかりません。", vbExclamation
Exit Sub
End If
On Error GoTo 0
' Wordを非表示で操作
wordApp.Visible = False
' PDFファイルをWordで開く
Set wordDoc = wordApp.Documents.Open(pdfPath)
' Word文書の内容を取得
wordText = wordDoc.Content.Text
' 改行コードを考慮して分割
If InStr(wordText, vbCrLf) > 0 Then
textLines = Split(wordText, vbCrLf) ' Windows形式の改行
ElseIf InStr(wordText, vbLf) > 0 Then
textLines = Split(wordText, vbLf) ' Unix形式の改行
ElseIf InStr(wordText, vbCr) > 0 Then
textLines = Split(wordText, vbCr) ' Mac形式の改行
Else
MsgBox "改行コードが見つかりません。", vbExclamation
Exit Sub
End If
' Excelのシートに行ごとに転記
For i = LBound(textLines) To UBound(textLines)
ThisWorkbook.Sheets(1).Cells(i + 1, 1).Value = textLines(i)
Next i
' Word文書を閉じる
wordDoc.Close SaveChanges:=False
wordApp.Quit
' オブジェクトを解放
Set wordDoc = Nothing
Set wordApp = Nothing
MsgBox "PDFからExcelへの転記が完了しました(行ごとに分割)。", vbInformation
End Sub