0
1

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 3 years have passed since last update.

VBAはじめました -データ範囲と最終行の取得ー

Last updated at Posted at 2020-12-22

#データ範囲の取得
A2からB6がデータ範囲として
#####1.CurrentRegionを使って

Dim Rg As Range
Set Rg = Range("A1").CurrentRegion

#####2.1行目が項目の時は

Set Rg = Rg.Offset(1, 0).Resize(Rg.Rows.Count - 1)
'または
Set Rg = Intersect(Rg, Rg.Offset(1, 0))

これでデータ範囲(項目行無し)になります。
#データ範囲の活用
####1.最終行の取得

Dim Gyou As Double
Gyou = Rg.Rows(Rg.Rows.Count).Row

別の方法だと

Dim Gyou As Double
Gyou = Range("A1").Offset(Rows.Count - 1, 0).End(xlUp).Row
'
Gyou = Range("A" & Rows.Count).End(xlUp).Row
'
Gyou = Sheets(1).Columns("A").Find("*", , xlValues, , , xlPrevious).Row

####2.各行を順次取得には
#####a.Range内の行を取得する方法

Dim gRg As Range
For Each gRg In aRg.Rows
    Debug.Print gRg.Address
Next

#####b.1列のRange内の行番号で指定する方法

Dim i As Double
For i = 1 To Rg.Columns(1).Rows.Count
    Debug.Print Rg.Rows(i).Address
Next

#####c.1列のRangeをひとつずつ取得して指定する方法

Dim gRg As Range, hRg As Range, dRg As Range
Set hRg = Rg.Columns(1)
For Each dRg In hRg
    Set gRg = Rows(dRg.Row)
    Debug.Print gRg.Address
Next

これがエラーとなる

For Each dRg In Range("A2:A6")
    Set gRg = Rows(dRg.Row)
    Debug.Print gRg.Address
Next

これは動く、違いは??
Rg.Columns(1)で1列に絞ったこと??
一応動くようにはなったが、一つしかエリアがないのに
Areasで拾わないといけない

Dim cRg As Range, gRg As Range, hRg As Range, dRg As Range
For Each cRg In hRg.Areas
    For Each dRg In cRg
    Set gRg = Rows(dRg.Row)
    Debug.Print gRg.Address
    Next
Next

#####c-1.このままだと1行指定なので

Set gRg = Rows(dRg.Row)

をIntersectを使って

Set gRg = Intersect(Rg, Rows(dRg.Row))

これで データ範囲の各行を取得できる。

#####c-2.別の列の指定

Set gRg = Intersect(Rows(dRg.Row), Range("D:F"))
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?