我正在创建将遍历数字列表并内插一系列“新Xs”的代码,而我要做的是不必修改代码以遍历不同范围的代码。单元格,我想在电子表格中选择单元格的范围,然后在现有数据旁边输出新数据。
我想知道是否有某种方式可以索引选定的范围,以便可以用于循环。
Private Sub Test_Click()
Dim rng As Integer, num As Integer
Dim xLower As Double, yLower As Double, xNew As Double
Dim xHigher As Double, yHigher As Double, yNew As Double
xNew = 0
For num = 1 To 28
xNew = xNew + 0.01
xLower = 0
yLower = 0
xHigher = 1.26
yHigher = 0
For rng = 2 To 108
If xNew - ActiveSheet.Cells(rng, 1).Value < xNew - xLower And ActiveSheet.Cells(rng, 1) < xNew Then
xLower = ActiveSheet.Cells(rng, 1).Value
yLower = ActiveSheet.Cells(rng, 3).Value
ElseIf xNew + ActiveSheet.Cells(rng, 1).Value < xNew + xHigher And ActiveSheet.Cells(rng, 1) > xNew Then
xHigher = ActiveSheet.Cells(rng, 1).Value
yHigher = ActiveSheet.Cells(rng, 3).Value
End If
Next rng
yNew = (xNew - xLower) / (xHigher - xLower) * (yHigher - yLower) + yLower
Cells(num, 7) = yNew
Cells(num, 6) = xNew
Next num
End Sub
答案 0 :(得分:3)
将所选内容设置为要遍历的范围,并确定该范围内左上方单元格的位置,例如:
dim ulRow as long, ulCol as long, selrng as range
ulRow = selection.row
ulCol = selection.column
Set selrng = application.selection
然后您可以循环显示该信息,或输出相对于该范围的信息,例如
for each cl in selrng
if isempty(cl) then cells(ulRow,ulCol+1).value = "moo"
next cl
编辑1:
添加一种在需要的情况下查找最后一个单元格的行/列的方法:
With selrng
lr = .row + .rows.count - 1
lc = .column + .columns.count - 1
end with
然后您可以像这样循环播放:
For i = ulRow to lr
if cells(i,lc).value <> 0 then cells(i,lc+1).value = "moo"
next i