将文本编号转换为值

时间:2016-05-06 23:45:45

标签: vba excel-vba excel-formula excel

我有来自Cell A17的以下值:A29

Col A      ColH   ColI
02494/1    191    191  Average  
02585/3    77     77   Average
02341/1    22     131 (Average for same ID in ColA)
02341/1    218

我需要根据Col A中的相同ID对Col H中的值进行平均,并将平均值放在Col I中。由于Col A ID是字符串,因此我在Col I中没有收到错误#N / A.我的代码首先尝试将ID转换为值。

    Sub conver()
    Range("A17:A20").Select
    With Selection
    Selection.NumberFormat = "General"
    .Value = .Value
    End With
    End Sub 

然后

    Sub averag()
    With Worksheets("averages")
Range("I17:I" & .Cells(.Rows.Count, 1).End(xlUp).Row).Formula = "=   IF(A17<>A16,AVERAGEIF(A17:INDEX($A17:INDEX(A16:A55,MATCH(1E+99,A16:A55)+1),MATCH(TRUE,(INDEX($A17:INDEX(A16:A55,MATCH(1E+99,A16:A55)+1)<>A17,)),0)),A17,H17:INDEX($H17:INDEX(H17:H55,MATCH(1E+99,A16:A55)+1),MATCH(TRUE ,(INDEX($A17:INDEX(A16:A55,MATCH(1E+99,A16:A55)+1)<>A17,)),0))),"""")"
    End With

    End Sub

但它尚未奏效。可以有人帮助这个。或者有其他方法可以做到这一点。我无法更改ID格式。谢谢。

1 个答案:

答案 0 :(得分:0)

已修改:为&#34;无限制&#34;添加了解决方案范围

无需任何列A值转换

如果您的相关范围位于工作表的第17行和第29行之间,并且平均值为#34;那么就这样:

Sub averag()
     Worksheets("averages").Range("A17:A29").SpecialCells(xlCellTypeConstants, xlTextValues).Offset(, 8).FormulaR1C1 = "=IF(COUNTIF(R17C1:RC1,RC1)>1,"""",AVERAGEIF(R17C1:R29C1,RC1,R17C8:R29C8))"
end sub

此外,该范围的下侧应该是动态的(即,不限于第29行),那么您可以如下所示:

Option Explicit

Sub averag()
Dim IDRng As Range

With Worksheets("averages")
    Set IDRng = .Range("A17:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
    IDRng.SpecialCells(xlCellTypeConstants, xlTextValues).Offset(, 8).FormulaR1C1 = "=IF(COUNTIF(R17C1:RC1,RC1)>1,"""",AVERAGEIF(" & IDRng.Address(, , xlR1C1) & ",RC1," & IDRng.Offset(, 7).Address(, , xlR1C1) & "))"
End With

End Sub