我在 Excel 电子表格中有一张表格。在此表中,我想从列 AP2 : AW2 向下运行到表的末尾并执行 2 个操作。一个我想将单元格值从文本转换为数字。其次,我会将每个单元格除以 100。到目前为止,我的代码包含两个在按下 Ctrl n 时触发的宏。它们可以工作,但被硬编码到第 2000 行,而不是找到表格的末尾(有时表格可能多于或少于 2000 行)。我也不认为拥有两个宏可能就那么有效。对此的任何帮助将不胜感激!
Sub Number_Conversion()
'Convert text to number
With Sheet1.Range("AP2:AW2000")
.NumberFormat = "Number"
.Value = .Value
End With
End Sub
Sub Divide_By()
'Divide number by 100
'declare variables
Dim ws As Worksheet
Dim rng As Range
Dim myVal As Range
Set ws = Sheet1
Set rng = ws.Range("AP2:AW2000")
For Each myVal In rng
If myVal.Value > 0 Then
myVal = myVal.Value / 100
End If
Next myVal
End Sub
这就是我的做法:
Sub try_this()
'declarations
Dim x As Long, y As Long, myArr, last_row As Long
'find last row in AP:AW range
last_row = Sheet1.Range("AP:AW").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'using the range down to last_row
With Sheet1.Range("AP2:AW" & last_row)
'copy range values to an array
myArr = .Value2
'cycle through the array horizontally
For x = 1 To UBound(myArr)
'.. and vertically
For y = 1 To UBound(myArr, 2)
'divide value by 100 if it equates to more than zero
If myArr(x, y) > 0 Then myArr(x, y) = myArr(x, y) / 100
Next
Next
'write array back to the range
.Value2 = myArr
End With
End Sub
感谢 Oscar 指出我遗漏的部分。现在,无论需要多少行,这都将动态工作。