vba - 循环遍历行并将单元格值存储为变量以运行公式,最终结果在另一个单元格中

标签 vba excel loops variables

excel
我想扫描每一行并提取某些单元格并将它们存储为变量。当我到达行尾时,我想运行一系列公式和 vlookup。我已经设置了所有公式和 vlookup,但是我需要扫描每一行,然后获取这些公式的结果并将它们放回另一个单元格。这是示例代码

Dim height As Double
Dim weight As Double
Dim gender As String
Dim newWeight as Double

'I'd like to set the loop here
'for each row do this
height = d2.value
weight = f2.value
gender = k2.value

'then run through my equations
If gender = "F" and weight < 20 Then
 newWeight = weight + 5
ElseIf gender = "F" and weight > 20 Then
 newWeight = weight -2
End If

l2.value = newWeight.value
'Then clear variables and run through the new row

我的方程比那个复杂一点,但我认为这会让我开始。

**编辑:我需要引用我正在使用的工作表吗?我打赌我会

最佳答案

见下面的代码

Sub temp()

    Dim height As Double
    Dim weight As Double
    Dim gender As String
    Dim newWeight As Double

    Dim lastRow As Integer
    lastRow = Range("C" & Rows.Count).End(xlUp).Row

    For i = 2 To lastRow
        'I'd like to set the loop here
        'for each row do this
        height = Range("D" & i).Value
        weight = Range("F" & i).Value
        gender = Range("K" & i).Value

        'then run through my equations
        If gender = "F" Then
            If weight < 20 Then
                newWeight = weight + 5
            ElseIf weight > 20 Then
                newWeight = weight - 2
            End If
        End If

        Range("L" & i).Value = newWeight
        'Then clear variables and run through the new row
    Next i

End Sub

您还需要弄清楚如果 weight = 20 会发生什么:P

关于vba - 循环遍历行并将单元格值存储为变量以运行公式,最终结果在另一个单元格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41274634/

相关文章:

excel - VBA 查找和替换行条目

java - 如何将 i 值插入到变量中?

Python - 通过 pandas 数据帧迭代并分配和有条件更新日期时间变量

vba - HTTPS POST 请求 VBA

vba - 等待表单在 MS Access VBA 中完成更新

vba - 声明关闭时编译错误

VBA 复制和粘贴方法不起作用

sql-server - SSIS完全忽略Excel列

vba - 在图表中添加辅助轴

c++ - 如何使用由 for 循环创建的 vector vector 构建链表?