VBA将列读入数组并基于两列的IF条件总和值

编程入门 行业动态 更新时间:2024-10-17 15:32:18
本文介绍了VBA将列读入数组并基于两列的IF条件总和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

正如@sktneer在我以前的查询中正确建议的那样,当处理大数据时,将数据读入数组.

As @sktneer rightly suggested in my previous query to read data into an Array when dealing with large data.

我想通读范围A的数组到最后,如果A1中的值等于"L",则添加B1 + C1

I want to Read through an array of Range A to the end and if the value in A1 is equal to "L" then add B1 + C1

我正在将此公式转换为以下代码=IF(A1="Male",C1+D1,FALSE)

I am converting this formula to below code =IF(A1="Male",C1+D1,FALSE)

Sub ANewMacro() Dim lr As Long, i As Long, j As Long Dim c, d, x, y() lr = Cells(Rows.Count, 1).End(xlUp).Row x = Range("A1:A" & lr).Value c = Range("C1:C" & lr).Value d = Range("D1:D" & lr).Value ReDim y(1 To UBound(x, 1), 1 To 1) j = 1 For i = 1 To UBound(x, 1) If x(i, 1) = "L" Then y(i, 1) = c(i, 1) + d(i, 1) j = j + 1 ElseIf x(i, 1) = "S" Then y(i, 1) = c(i, 1) + d(i, 1) j = j + 1 Else y(i, 1) = "NULL" j = j + 1 End If Next i Range("B1").Resize(UBound(y), 1).Value = y End Sub

代码按预期工作,但想知道声明多个范围的方法是否正确以及执行情况.

The code works as desired but wanted to know if the method of declaring multiple range is correct and also the execution.

我必须遍历10万行

推荐答案

您可以将整个数据读取到单个数组中,该数组称为多维数组.

You can read the whole data into a single Array which will be called multidimensional array.

根据您现有的代码,您可以尝试类似的操作...

As per your existing code, you may try something like this...

Sub ANewMacro() Dim lr As Long, i As Long, j As Long Dim x, y() lr = Cells(Rows.Count, 1).End(xlUp).Row x = Range("A1:D" & lr).Value ReDim y(1 To UBound(x, 1), 1 To 1) j = 1 For i = 1 To UBound(x, 1) If x(i, 1) = "L" Then y(i, 1) = x(i, 3) + x(i, 4) ElseIf x(i, 1) = "S" Then y(i, 1) = x(i, 3) + x(i, 4) Else y(i, 1) = "NULL" End If j = j + 1 Next i Range("B1").Resize(UBound(y), 1).Value = y End Sub

在上面的代码中x(i,1)代表A列中的数据,x(i,3)代表C列中的数据,x(i,4)代表D列中的数据.

In the above code x(i, 1) represents data in column A, x(i, 3) represents data in column C and x(i, 4) represents the data in column D.

现在,因为如果列A为"L"或"S",则您执行的是相同的计算,因此您可以像下面那样替换For循环...

Now since if the Column A is either "L" or "S" you are performing the same calculation so you may replace the For Loop like below...

For i = 1 To UBound(x, 1) If x(i, 1) = "L" Or x(i, 1) = "S" Then y(i, 1) = x(i, 3) + x(i, 4) Else y(i, 1) = "NULL" End If j = j + 1 Next i

更多推荐

VBA将列读入数组并基于两列的IF条件总和值

本文发布于:2023-11-21 23:33:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615106.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   总和   条件   VBA

发布评论

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

>www.elefans.com

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