我有兴趣修改下面的代码,以便它将每个其他列的值除以100而不是固定列X.我知道这可能是通过使用计数器并在while循环中将其递增2来实现的,但是我用一个整数替换列X引用时遇到了麻烦:
Sub Divide()
Dim element As Range
Dim MaxRows As Long
With Worksheets("Returns")
MaxRows = .Cells(.Rows.Count, "X").End(xlUp).Row
End With
For Each element In Worksheets("Returns").Range("X1:X" & MaxRows)
If IsNumeric(element.Value) Then
element.Value = element.Value / 100
End If
Next
End Sub
答案 0 :(得分:0)
使用循环绝对是可行的方法:
Sub Divide()
Dim element As Range
Dim MaxRows As Long
Dim col As Long
With Worksheets("Returns")
For col = 2 To .Cells(1, .Columns.Count).End(xlToLeft).Column
MaxRows = .Cells(.Rows.Count, col).End(xlUp).Row
'Use the "Range(cell reference, cell reference)" syntax to define the range
For Each element In .Range(.Cells(1, col), .Cells(MaxRows, col))
If IsNumeric(element.Value) Then
element.Value = element.Value / 100
End If
Next
Next
End With
End Sub
执行除法的另一种方法可能是执行复制/粘贴特殊值 - 除法,但这需要先将100
放入某个虚拟单元格中。
答案 1 :(得分:0)
另一个答案可能有效,但这与原始代码更相似。
Sub Divide()
Dim element As Range
Dim MaxRows As Long
With Worksheets("Returns")
MaxRows = .Cells(.Rows.Count, "X").End(xlUp).Row
End With
Dim holdRange as Range
Dim i as Integer
i = MaxRows
While i > 0
If IsNumeric(Worksheets("Returns").Range("X1:X" & i)) Then
Worksheets("Returns").Range("X1:X" & i).Value = Worksheets("Returns").Range("X1:X" & i).Value / 100
End If
i = i - 2
Loop
End Sub
答案 2 :(得分:0)
{Sub example()
Dim rng As Range, cell As Range
Set rng = Application.Selection
For Each cell In rng
cell.Value = cell.Value / 1000
Next cell
End Sub}