VBAを使用してExcelマクロで可変範囲を定義したいとします。最初のセルは常にA25ですが、最後のセルは収集されたデータの数に応じて移動しています。これはE35、E58などとすることができます。Visual Basic for Excelの可変範囲
1
A
答えて
0
範囲を2つのリミットセルとして定義できます。あなたがワークシート「WS」で作業しているとしましょう:
オプション1:
Dim rng As Range
Dim cl1 As Range: Set cl1 = ws.Range("A25")
Dim cl2 As Range
Set cl2 = ws.Range("E35") 'Or something else'
Set rng = ws.Range(cl1, cl2)
1
は、2つのオプションがあり、あなたが定義するために探しているRange
が連続している(以下のスクリーンショットを参照してください):
簡単なアプローチが行います。
Option Explicit
Sub DefRange()
Dim Rng As Range
With Worksheets("Sheet1") '<-- modify "Sheet" to your sheet's name
Set Rng = .Range("A25").CurrentRegion
Debug.Print Rng.Address '<-- for debug: will show A25:E35
End With
End Sub
オプション2:範囲あなたが定義するために探しているが、中間の(下のスクリーンショット)で、空行を持っています
、その後、従来の方法は間違った範囲となります
Option Explicit
Sub DefRange()
Dim Rng As Range
Dim LastRow As Long
Dim LastCol As Long
With Worksheets("Sheet1") '<-- modify "Sheet" to your sheet's name
Set Rng = .Range("A25").CurrentRegion
Debug.Print Rng.Address '<-- for debug: will show A25:E35 ***WRONG***
'Search for any entry, by searching backwards by Rows.
LastRow = .Cells.Find(What:="*", After:=.Range("A25"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'Search for any entry, by searching backwards by Columns.
LastCol = .Cells.Find(What:="*", After:=.Range("A25"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Set Rng = .Range(.Cells(25, "A"), .Cells(LastRow, LastCol))
Debug.Print Rng.Address '<-- for debug: will show A25:F37 ***CORRECT***
End With
End Sub
+0
@Eric Justusここで答えを試してみましたか?彼らは働いたのですか? –
0
だけで、E列内の行をカウント
Sub Button1_Click()
Dim LstRw As Long
Dim Rng As Range, x
LstRw = Cells(Rows.Count, "E").End(xlUp).Row
x = IIf(LstRw > 25, LstRw, 25)
Set Rng = Range("A25:E" & x)
Rng.Select
End Sub
+0
あなたのおかげで、うまくいきました。 –
関連する問題
- 1. Excel VBA AVERAGE(可変範囲)
- 2. Visual Basic for Applicationsアニメーションテキスト
- 3. Visual Basic OpenLinks Excel
- 4. ExcelでVisual Basicで選択範囲の上にセルを設定するには?
- 5. レガシーコードVisual Basic for C#
- 6. ExcelのVisual Basicのコピーシート
- 7. Visual BasicカウンタループExcelで
- 8. 玉の可変範囲
- 9. 可変範囲のVBA sumif
- 10. Visual Basic Excelの条件式
- 11. Visual Basic EditorのマージンExcel 2016
- 12. Excel 2007 VBA範囲変数参照範囲外のセル
- 13. Visual Basic for ExcelでJavaと同等の「。*」とは何ですか?
- 14. Visual Basicでの可変引数リスト?
- 15. Excelの範囲
- 16. Visual Basic for Microsoft Accessトレーニング
- 17. numpyのインデックス可変範囲
- 18. 可変範囲の制御
- 19. 可変範囲のVBAオートフィルタ
- 20. forループエラー:範囲
- 21. Excel - 範囲の値のリストを範囲に変換
- 22. Visual Basic for Excel:列ヘッダーを削除します。
- 23. 範囲内の可変シート名を持つExcel式
- 24. 可変範囲Google Script
- 25. ハスケル:whileM_可変範囲?
- 26. excelで可変文字列範囲を定義する方法
- 27. Visual Basicの選択「インデックスが範囲外です」の並べ替え
- 28. Excel vba - 範囲の要素
- 29. for CoffeeScriptの範囲のループ
- 30. Excel名前付き範囲変更イベント
これを変数に追加するには、contiguous rangeを使用します。try rr = range( "a25")。currentregion、文字列として範囲を取得するtry str = range( "a25")。currentregion.address – Zerk
収集していますか? A25で始まる領域のデータ、またはその領域に書き込もうとしていますか?前者の場合は、Zerkが示したようにRange.CurrentRegionがおそらく最善の策です。 – SgtStens