确定三个值之间的百分比差异的代码

时间:2017-05-17 21:17:16

标签: excel openpyxl python-3.6

我想找到单个列中三个值之间的百分比差异,并将差异百分比转移到新列

Lets say I have the following values to compare: 
**Value1** = 5 
**Value2** = 8 
**Value3** = 2

我需要从Value1和Value3中减去Value2,我还需要从Value3中减去Value1。

我想要一个简单的方法来找到一式三份的最大值并减去剩下的两个值来找到百分比差异然后找到第二个最高值并减去最低值以找到它的百分比差异。

也许我接近这一切都错了。任何帮助是极大的赞赏。

****CODE*****

import openpyxl
from openpyxl.worksheet.datavalidation import DataValidation

wb = openpyxl.load_workbook('05.16.17 CaMKII Sean RD.xlsx', read_only= False, data_only = True)


sheet = wb['Sheet1']

### Protein Max Value for Triplicate 

for i in range(2,3):
    sheet['D{}'.format(i)] = '=max(C2:C4)'.format(i)
for i in range(2,3):
    sheet['E{}'.format(i)] = '=((D2-C2)/(D2+C2) * 100)'.format(i)
for i in range(3,4):
    sheet['E{}'.format(i)] = '=((D2-C3)/(D2+C3) * 100)'.format(i)
for i in range(4,5):
    sheet['E{}'.format(i)] = '=((C3-C2)/(C2+C3) * 100)'.format(i)


wb.save('camdatapolishedoutput.xlsx')

1 个答案:

答案 0 :(得分:1)

我没有清楚地理解您的代码,但似乎您正在寻找 FormatPercent 公式。此外,您还必须更改代码的许多部分。在下面我已经纠正了很多,但只要我不知道你真正想要做什么,剩下的就是你的。

 Dim wb as Workbook, sheet as Worksheet
 Dim wsArrD2 As Range, wsArrC2 As Range, wsArrC3 As Range, wsArrC4 As Range
 Dim yourdesktopaddress as String
 yourdesktopaddress = CreateObject("WScript.Shell").specialfolders("Desktop")
 Set wb = Application.Workbooks.Open(yourdesktopaddress & "\05.16.17 CaMKII Sean RD.xlsx")
 ''This code finds your Desktop address and opens the specific file.

 Set sheet = wb.Sheets("Sheet1")
 'I assume you were looking for information from that file's Sheet1 sheet.

 Set wsArrD2 = sheet.Range("D2")
 Set wsArrC2 = sheet.Range("C2")
 Set wsArrC3 = sheet.Range("C3")
 Set wsArrC4 = sheet.Range("C4")

 Dim maxC as Long, PercentVar1 as String
 Dim PercentVar2 as String, PercentVar4 as String
'You should define your '%' variables as String otherwise you will get an Run Time 13 Error'

 maxC = Evaluate("=MAX(C2:C4)")
 PercentVar1 = FormatPercent((wsArrD2 - wsArrC2) / (wsArrD2 + wsArrC2), 2)
 PercentVar2 = FormatPercent((wsArrD2 - wsArrC3) / (wsArrD2 + wsArrC3), 2)
 PercentVar3 = FormatPercent((wsArrC3 - wsArrC2) / (wsArrC3 + wsArrC2), 2)
  

在此公式中,您不需要将其乘以100,因为:    FormatPercent返回格式为百分比(即乘以100)的表达式,其尾部为%字符。

For more info please visit FormatPercent Function (Visual Basic) on msdm.microsoft