使用VBA划分不相邻的单元格

时间:2013-07-25 10:47:00

标签: excel vba excel-vba

有关如何解决此问题的任何建议?

(更新)

numeratordenominator是包含整数值的范围。

我想按照这些范围的单元格进行除法,例如:

numerator(1)/denominator(1) numerator(2)/denominator(2) ... 

并将结果粘贴到quotient。所有范围都具有相同的尺寸,并且是行向量尺寸。

我的解决方案尝试:

Sub DivRanges()
    Dim targetRng As Range, sourceRng1 As Range, sourceRng2 As Range    
    For i = 1 To targetRng.Cells.Count
         quotient.Cells(i).Value = numerator.Cells(i).Value / denominator.Cells(i).Value
    Next i
End Sub

问题是DivRanges不会遍历范围的每个值,因为它们是行向量。相反,随着我的成长,它会逐渐下降。范围的单元格不相邻时会发生此问题。

这是基于mehow代码的问题显示。结果是在工作表中选择的单元格。

Example

1 个答案:

答案 0 :(得分:1)

如果您的电子表格符合

bef

那么这段代码

Sub DivRanges()
    Dim quotient As Range, numerator As Range, denominator As Range

    Set numerator = Range("A1:D1")
    Set denominator = Range("A2:D2")
    Set quotient = Range("A3:D3")

    Dim i As Long
    For i = 1 To quotient.Count
        quotient.Cells(i).Value = numerator.Cells(i).Value / denominator.Cells(i).Value
    Next i
End Sub

给你

aft


<强> 更新

不相邻的细胞溶液

假设你的表

before

使用以下代码

Sub DivRanges()
    Dim quotient As Range, numerator As Range, denominator As Range

    Set numerator = Range("A1, C1, D1, E1")
    Set denominator = Range("A2, C2, D2, E2")
    Set quotient = Range("A3, C3, D3, E3")

    Dim c As Range
    Dim i As Long
    i = 0
    For Each c In quotient
        Range(c.Address) = Range(getNum(numerator.Address, i)) / Range(getNum(denominator.Address, i))
        i = i + 1
    Next

End Sub

Function getNum(str As String, i As Long) As String
    getNum = Split(str, ",")(i)
End Function

结果是

result