预计阅读时间: 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 将数组的大小增加 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