預計閱讀時間: 3 minuti
以下 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 將數組的大小增加 10dCellValues(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