从范围中检索列号

时间:2014-09-04 20:10:06

标签: vba excel-2007

如何从一系列单元格中检索列号,以便执行基于列的计算。

    Set rng = regSheet.Range("F" & i & ":K" & i)
    For Each cell In rng.Cells
        Select Case rng.Column
            Case 6
                sum = sum + (cell.Value * 5)
            Case 7
                sum = sum + (cell.Value * 15)
            Case 8
                sum = sum + (cell.Value * 5)
            Case 9
                sum = sum + (cell.Value * 5)
            Case 10
                sum = sum + (cell.Value * 10)
            Case 11
                sum = sum + (cell.Value * 20)

        End Select

3 个答案:

答案 0 :(得分:2)

尝试更改此行:

Select Case rng.Column

Select Case cell.Column

答案 1 :(得分:0)

=((F10 + H10 + I10) * 5) + (G10 * 15) + (J10 * 10) + (K10 * 20)

编辑:i的值是不变的。我认为上面的代码是10。这个公式有帮助吗?

假设你不想使用公式&使用VBA。在这种情况下,您不需要编写for循环,因为您正在遍历单行的单元格。

Sub test()
Dim total As Double
Dim i As Integer
Dim Rng As Range

i = 10
Set Rng = Sheet1.Range("F" & i & ":K" & i)

total = total + (Rng.Cells(1).Value * 5)
total = total + (Rng.Cells(2).Value * 15)
total = total + (Rng.Cells(3).Value * 5)
total = total + (Rng.Cells(4).Value * 5)
total = total + (Rng.Cells(5).Value * 10)
total = total + (Rng.Cells(6).Value * 20)

MsgBox total
End Sub

答案 2 :(得分:0)

我想我理解你的问题,但你的代码很模糊,有点静态。由于柱子可以移动,因此这种寻址细胞的方法很草率。我建议你使用表格。

无论哪种方式,都要给这个代码一个镜头,看看它是否有帮助。

Public Sub test()
Dim wsSheet As Worksheet
Dim Rng As Range
Dim i As Long   'Not sure the purpose of this var?
Dim sum As Long 'Not sure the purpose of this var?

Set wsSheet = Worksheets("regSheet")
Set Rng = wsSheet.Range("F" & i & ":K" & i)
i = 1 'Not sure the purpose of this variable?

With Rng
    Dim xCol As Range
    For Each xCol In Rng.Columns
        Dim xCell As Range
        For Each xCell In xCol
            Select Case xCell.Column
                Case 6
                    sum = sum + (xCell.Value * 5)
                Case 7
                    sum = sum + (xCell.Value * 15)
                Case 8
                    sum = sum + (xCell.Value * 5)
                Case 9
                    sum = sum + (xCell.Value * 5)
                Case 10
                    sum = sum + (xCell.Value * 10)
                Case 11
                    sum = sum + (xCell.Value * 20)
            End Select
        Next xCell
    Next xCol
End With

End Sub