推定読書時間: 3 分
次の Sub プロシージャは、空白セルが見つかるまで、アクティブなワークシートの列 A のセルから値を読み取ります。値は配列に格納されます。この簡単な Excel マクロの例は、次の使用法を示しています。
Do Until
;Ubound
組み込み (配列の最大のインデックスを返します)。' Sub procedure store values in Column A of the active Worksheet
' into an array
Sub GetCellValues()
Dim iRow As Integer ' stores the current row number
Dim dCellValues() As Double ' array to store the cell values
iRow = 1
ReDim dCellValues(1 To 10)
' Do Until loop to extract the value of each cell in column A
' of the active Worksheet, as long as the cell is not blank
Do Until IsEmpty(Cells(iRow, 1))
' Check that the dCellValues array is big enough
' If not, use ReDim to increase the size of the array by 10
If UBound(dCellValues) < iRow Then
ReDim Preserve dCellValues(1 To iRow + 9)
End If
' Store the current cell in the CellValues array
dCellValues(iRow) = Cells(iRow, 1).Value
iRow = iRow + 1
Loop
End Sub
このプロシージャは、アクティブなワークシートの列 A の値を配列に格納します。次の点に注意してください。
Do Until
アクティブなワークシートの列 A の各セルの値を抽出し、空白セルを無視しますIf UBound(dCellValues) < iRow
」 dCellValues 配列が情報を保持するのに十分な大きさであることを確認します。そうでない場合は、ReDim を使用して配列のサイズを 10 増やしますdCellValues(iRow) = Cells(iRow, 1).Value
現在のセルをCellValues配列に格納します次の Sub プロシージャは、「Sheet2」という名前のワークシートの列 A から値を読み取り、その値に対して算術演算を実行します。結果の値は、現在アクティブなワークシートの列 A に出力されます。
このマクロは次のことを示しています。
Do Until
;' Sub procedure to loop through the values in Column A of the Worksheet
' "Sheet2", perform arithmetic operations on each value, and write the
' result into Column A of the current Active Worksheet ("Sheet1")
Sub Transfer_ColA()
Dim i As Integer
Dim Col As Range
Dim dVal As Double
' Set the variable 'Col' to be Column A of Sheet 2
Set Col = Sheets("Sheet2").Columns("A")
i = 1
' Loop through each cell of the column 'Col' until
' a blank cell is encountered
Do Until IsEmpty(Col.Cells(i))
' Apply arithmetic operations to the value of the current cell
dVal = Col.Cells(i).Value * 2 + 1
' The command below copies the result into Column A
' of the current Active Worksheet - no need to specify
' the Worksheet name as it is the active Worksheet.
Cells(i, 1) = dVal
i = i + 1
Loop
End Sub
シートの特定の範囲のセルが更新されたときに起動する簡単な VBA マクロを作成してみましょう。列 B (B4 から B11) の変更を追跡し、列 A に変更の日時を記録するとします。
次のように進めてみましょう。
Developer
オプション「」をクリックしますVisual Basic
」をクリックして VBA エディタを開きます。 Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("B1:B10")) Is Nothing Then
Target.Range("A1:A1").Value = Now
End If
End Sub
マクロを有効にしてワークブックを保存します (たとえば、.xlsm ファイルとして)。
これで、列 B (行 1 から行 10) のセルを更新するたびに、列 A のセルに現在の日付と時刻が自動的に表示されます。
Ercole Palmeri
先週の月曜日、フィナンシャル・タイムズ紙はOpenAIとの契約を発表した。 FT は世界クラスのジャーナリズムにライセンスを供与しています…
何百万人もの人々がストリーミング サービスに月額料金を払っています。あなたは…というのが一般的な意見です。