0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ノート】VBA②オブジェクトとその扱い方

0
Posted at

VBAにおけるオブジェクトとは

Excel上のあらゆる要素のこと

おもなオブジェクトの例

Application:Excel全体 ※通常は省略することが多い
Workbook:ブック(Excelファイル)
Range:セルの集合

オブジェクトの階層構造

Workbooks("サンプル.xlsm").Worksheets("sheet1").Range("A1").Value = 1

' Workbooks("サンプル.xlsm") →ブックの指定
'  Worksheets("sheet1") →シートの指定
'   Range("A1") →セルの指定
'     Value = 1 →プロパティの指定

※途中のオブジェクト記述を省略することもできるが、エラー回避や可読性向上のために省略せず書くことが推奨されている。

オブジェクト変数

VBAではオブジェクトを変数に代入できる。その際は必ずSetステートメントを使う。

オブジェクト変数の使い方

Sub Example()
    Dim currentSheet As Worksheet ' シートオブジェクトを格納する変数

    Set currentSheet = Thisworkbook.Sheets("sheet1")

    ' 代入したシートを使って値を操作する
    currentSheet.Range("A1").Value = "こんにちは"
    currentSHeet.Range("B1").Value = "Hello"
End Sub

オブジェクト変数の解放

不要なオブジェクト変数にNothingを代入することで、メモリを解放できる。

Set currentSheet = Nothing
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?