6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

WordVBA汎用関数 (画像操作、文字列操作、テーブル操作)

Posted at

WordVBA汎用関数

※以下全てのdoc変数はWord.Document

画像操作:

1.画像をワードに適用する関数

Public Function Applyimg(ByVal imgPath As String, ByRef shpPlace As Object) As Object
    Dim shp As Object
    Set shp = shpPlace.AddPicture(imgPath)
    Set Applyimg = shp
End Function

キーポイント: 引数shpPlaceを用いて、画像挿入の位置を指定する。

2.画像の掲載位置を設定する関数

Public Function ApplyImgPlace(ByRef shp As Object, ByVal setPlace As String)
    shp.WrapFormat.Type = wdWrapInline
    shp.Anchor.ParagraphFormat.Alignment = setPlace
End Function

キーポイント:setPlace(0左寄せ 1中央 2右寄せ)

文字列操作:

1.特定の文字列を書き換える関数

Public Function ConvertWords(ByVal isChangeAll As Boolean, ByVal wordsBeChange As String, ByVal wordsToChange As String)
    If isChangeAll = False Then
            doc.Content.Find.Execute FindText:=wordsBeChange, ReplaceWith:=wordsToChange, Replace:=wdReplaceOne
    Else
            doc.Content.Find.Execute FindText:=wordsBeChange, ReplaceWith:=wordsToChange, Replace:=wdReplaceAll
    End If
End Function

キーポイント:変数isChangeがTrueの場合はFindした全ての対象を書き換える。Falseの場合は最初の一個を書き換える。

2.全体文字列スタイルを適用する関数

Public Function ApplyFontSetting(ByVal fontStyle As String)
    doc.Content.Font.name = fontStyle
End Function

テーブル操作:

1.行削除

Public Function DeleteRow(ByVal tableName As String, ByVal rowNum As String)
    Dim i As Integer
    For i = 1 To doc.Tables.Count
    If doc.Content.Tables(i).title = tableName Then
        doc.Content.Tables(i).Rows(rowNum).Delete
    End If
    Next i
 End Function

キーポイント:Wordのテーブルにタイトルを付けることで、特定のテーブルを取得する。

2.セル分割

Public Function SplitCell( _
 ByVal tableName As String, ByVal cellRow As String, _
 ByVal celCol As String, ByVal spRow As String, ByVal spNum As String _
 )
    Dim i As Integer
    For i = 1 To doc.Tables.Count
    If doc.Content.Tables(i).title = tableName Then
        doc.Content.Tables(i).cell(cellRow,cellCol).Split NumRows:=spRow, NumColumns:=spNum
    End If
    Next i
 End Function

キーポイント:Splitメソッドでセルを分割する。NumRowsとNumColumnsパラメータで分割したいセルの行数と列数を指定する。

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?