更改列中数值的符号(Changing the sign of numeric values in a column)

编程入门 行业动态 更新时间:2024-10-10 03:28:07
更改列中数值的符号(Changing the sign of numeric values in a column)

我在D列有数据。

D1列中有一个标题,D2向下有数字值。 我想选择列D中的所有数值(值的数量未知),并将它们乘以-1(替换D列中的当前值)。 我如何通过VBA代码来做到这一点?

如果我可以在Excel中使用公式,我只需将公式D2 * -1向下拖动; 但是,我需要VBA等价物。

I have data in column D.

There is a header in column D1 and numeric values in D2 downward. I would like to select all numeric values in column D (the number of values is unknown) and multiply them by -1 (replacing the current values in column D). How would I do this through VBA code?

If I could use formulas in Excel I would simply drag the formula D2*-1 downward; however, I need the VBA equivalent.

最满意答案

以100,000个随机值进行测试时,几乎可以立即进行以下工作:

Sub MultColDbyOne() Dim i As Long, n As Long, A As Variant n = Cells(Rows.Count, "D").End(xlUp).Row A = Range(Cells(2, "D"), Cells(n, "D")).Value For i = LBound(A) To UBound(A) A(i, 1) = -A(i, 1) Next i Range(Cells(2, "D"), Cells(n, "D")).Value = A End Sub

该子工作首先确定列D中的数据的最后一行,然后将其转移到VBA数组(这有点烦人,只有1列的2维数组),循环遍历该数组替换其中的每个数字其负面,然后将其转回。 这个array然后返回到Range策略在VBA中相当常见(且效率相当高)。

The following works almost instantaneously when tested with 100,000 random values:

Sub MultColDbyOne() Dim i As Long, n As Long, A As Variant n = Cells(Rows.Count, "D").End(xlUp).Row A = Range(Cells(2, "D"), Cells(n, "D")).Value For i = LBound(A) To UBound(A) A(i, 1) = -A(i, 1) Next i Range(Cells(2, "D"), Cells(n, "D")).Value = A End Sub

The sub works by first determining the last row with data in column D, then transferring it to a VBA array (which is, somewhat annoyingly, a 2-dimensional array with only 1 column), looping through that array replacing each number in it by its negative, then transferring it back. This Range to array then back to Range strategy is fairly common (and fairly efficient) in VBA.

更多推荐

本文发布于:2023-07-18 07:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1157054.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数值   符号   Changing   sign   values

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!