0
0

More than 3 years have passed since last update.

VBAの基本操作(関数)

Last updated at Posted at 2021-04-17

VBAの初心者向けに基本操作方法(関数)を紹介していきたいと思います。

【Instr関数】

A1「みかんぶどうりんご」から「りんご」がどこにあるか調べる
Dim str1 As String            '変数str1の設定
Dim str2 As String            '変数str2の設定
Dim instrNum As Long          '変数instrNumの設定
str1 = Cells(1, 1)            'str1の値をA1の文字列にする
str2 = "りんご"                 'str2の値をりんごとする
instrNum = InStr(str1, str2)  'str1からstr2を検索する
MsgBox str1 & vbLf _          'MsgBoxで何文字目にヒットしたかを表示する
& "検索文字:" & str2 & vbLf _
& instrNum & "文字目"

 InStr関数は、指定した文字列から任意の文字列を検索し、見つかった開始位置を数字で返す関数です。上記のコードではりんごが何文字目に含まれるかを検索します。

A1「みかんぶどうりんご」から「ぶどう」を取り出して表示する
Dim str1 As String
Dim str2 As String
Dim str3 As String
str1 = Cells(1, 1)
str2 = "ぶどう"
str3 = InStr(str1, str2)          'ぶどうが何文字目にヒットするかを検索
Cells(2, 1) = Mid(str1, str3, 3)  'ぶどうを取り出して表示する

 上記のコードではぶどうが何文字目に含まれるかを検索し、ヒットした文字数を使ってぶどうを取り出して表示しています。今回使ったMid関数は任意の文字列から特定の文字を取り出す時に使用します。

A1「みかんぶどうりんご」から「ぶどう」を「ブドウ」に変換する
Dim str1 As String
Dim str2 As String
str1 = Cells(1, 1)
str2 = Replace(str1, "ぶどう", "ブドウ")
Cells(2, 1) = str2

 Replace関数は文字通り文字列を置き換える際に使用します。

A1「みかん,ぶどう,りんご」をカンマ区切りで分割する(Mid)
Dim str1 As String
Dim str2 As String
Dim str3 As String
Dim str4 As String
Dim str5 As String

str1 = Cells(1, 1)
str2 = ","
str3 = InStr(str1, str2)
str4 = Mid(str1, str3 + 1)
str5 = InStr(str4, str2)

Cells(2, 1) = Mid(str1, 1, 3)
Cells(3, 1) = Mid(str4, 1, 3)
Cells(4, 1) = Mid(str4, str5 + 1, 3)

 かなり長い文章になってしまいましたね^^;
 こういった特定の文字を起点に文字列を分けたい場合には次に紹介するSplit関数を利用すると良いでしょう。

A1「みかん,ぶどう,りんご」をカンマ区切りで分割する(Split)
Dim str1 As Variant
Dim str2 As Variant
str1 = Cells(1, 1)
str2 = Split(str1, ",") 'カンマを起点に「箱」に格納する
Cells(2, 1) = str2(0)   '「箱」の1個目を取り出す
Cells(3, 1) = str2(1)   '「箱」の2個目を取り出す
Cells(4, 1) = str2(2)   '「箱」の3個目を取り出す

 およそ半分の内容で同じ動作になりましたね。Split関数は特定の文字を起点に分割して「箱」に格納するという機能があります。プログラミング言語は数をカウントする際に1からではなく0からスタートする点に注意しましょう。

【InputBox】

InputBoxに入力した値をセルに表示する
Dim buf As String
buf = InputBox("入力")
Cells(1, 1) = buf

 InputBoxは文字通り入力覧を表示して任意の場所に入力できる機能があります。

【Len関数】

A1とA2の文字数の合計をA3に表示する
str1 = Cells(1, 1)
str2 = Cells(2, 1)
Cells(3, 1) = Len(str1) + Len(str2)

 Len関数は文字数を取り出す関数となっています。

【FileDaialog】

フォルダを選択肢し、フォルダパスを表示する
With Application.FileDialog(msoFileDialogFolderPicker)
   .InitialFileName = ""
   If .Show = True Then
      Cells(1, 1) = .SelectedItems(1)
   End If
End With

 FileDaialogはフォルダを選択することでそこまでのパスを取り出す機能があります。
 パスというのはデータがどこに保存されているのかを示すものになります。これがないとマクロがフォルダを認識でき無いので開いているブック以外のファイルを参照する際は必須になります。

<補足1>
ファイルとはワードやエクセル等で作成したテキストデータのことでありフォルダとはファイルを入れておく箱のことである。(ディレクトリとも言う)

<補足2>
FileDialogはOSがWindowsでなければ動作しません。(正確にはこのままでは使えない)また、最新のWindowsの場合参照先がCドライブ外の場合インターネットに接続しないとパスを繋げなくなります。(クラウド扱いになっているから???)

フォルダ名を順番にセルへ表示する
Dim dlg As FileDialog
Dim SelectDir As String
Dim Fname As String
Dim Fcnt As Long

Set dlg = Application.FileDialog(msoFileDialogFolderPicker)
   If dlg.Show = False Then Exit Sub
SelectDir = dlg.SelectedItems(1)

Fcnt = 0
Fname = Dir(SelectDir & "\*.*")
Do While Fname <> "" 'フォルダが無くなるまで数える
   Fcnt = Fcnt + 1
   Cells(Fcnt, 1) = Fname
   Fname = Dir()
Loop

 上記のコードではフォルダに含まれる複数のファイルデータのタイトルを順番に表示していくと言う内容になっています。VBAの基本操作(プログラム制御)で説明したDo loopを使用してA1から順番に表示しています。

【Rnd関数】

1~10のランダムな数字をセルへ入力しその合計を算出する
Const low As Integer = 1
Const high As Integer = 10
Randomize
Dim i As Integer
j = 1
Do While j <= 5
   i = Int((high - low + 1) * Rnd + low)
      Cells(j, 1) = i
      j = j + 1
   Loop
Cells(6, 1) = WorksheetFunction.Sum(ActiveSheet.Range("A1", "A5"))

 Rnd関数は文字通りランダムな値を返す関数で、範囲を指定してその中から返すこともできる。

【Arry(箱)】

セルの中身をArryに格納し2番目を取り出す
Dim sArray(4) As String          '5つまで入る箱を用意する
i = 1
Do While i <= 5
   sArray(i - 1) = Cells(i, 1)   '1から順番に「箱」に格納する
   i = i + 1
   Loop
Cells(1, 2) = sArray(1)          '「箱」の2番目を取り出す

 Arryは配列(箱)を意味するもので、上記のコードの様に中に入れては取り出すと言うことができます。

 今回は新しい関数が沢山出てきましたがどれも頻繁に使用されるものです。特に配列に入れては取り出すと言う動作はなかなかイメージしにくいかもしれませんが何度も使ってみて慣れておくと良いでしょう。

0
0
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
0
0