在 win32com 中将参数传递给 Excel 的 Range.Value(RangeValueDataType)

Passing parameter to Excel's Range.Value(RangeValueDataType) in win32com

我正在尝试使用 win32com/python 获取 Excel 中一系列单元格的内部颜色。循环遍历每个单元格不是一个选项,因为这需要 3 到 5 秒才能完成,而颜色每秒都在变化。

使用 Range.Value(11) 似乎有帮助,但 win32com 不喜欢将任何参数传递给 Range.Value。

import win32com.client as win32
excel = win32.Dispatch('excel.application')

fileName = r"myFile.xlsm"
myBook = excel.Workbooks(fileName)
mySheet = myBook.Sheets('Sheet1')
myRange = mySheet.Range('I3:AL32')

myState = myRange.Value # is acceptable but useless
myState = myRange.Value(11) # TypeError: 'tuple' object is not callable

在 Excel 中的 VBA 中执行 myRange("I3:AL32").Value(11) 工作正常,但我无法创建自定义 UDF 并使用 Application.Run在 win32com 中要么是因为基础 Excel 文件中已经有 VBA 代码 运行(这是首先改变单元格颜色的原因)。

还有其他方法可以将该参数传递给 Range.Value 吗?

我不确定这是你想要的结果,不幸的是它没有使用 win32com.client,而是 comtypes.client,但如果你尝试:

import comtypes.client # unfortunately not win32com
excel = comtypes.client.CreateObject('Excel.Application')

fileName = r"myFile.xlsx" # I used .xlsx but should work with .xlsm
myBook = excel.Workbooks.Open(fileName)
mySheet = myBook.Sheets('Sheet1')
myRange = mySheet.Range('I3:AL32')

myState = myRange.Value(11) #with comtypes.client you can use the parameter 11
print myState

你打印这样的东西:

<?xml version="1.0"?>
......
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font ss:FontName="Calibri" x:Family="Swiss" ss:Size="11" ss:Color="#000000"/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
  <Style ss:ID="s21">
   <Interior ss:Color="#00B0F0" ss:Pattern="Solid"/>
  </Style>
  <Style ss:ID="s23">
   <Interior ss:Color="#E26B0A" ss:Pattern="Solid"/>
  </Style>
  <Style ss:ID="s25">
   <Interior ss:Color="#00FF00" ss:Pattern="Solid"/>
  </Style>
  <Style ss:ID="s26">
   <Interior ss:Color="#C0504D" ss:Pattern="Solid"/>
  </Style>
  <Style ss:ID="s27">
   <Interior ss:Color="#60497A" ss:Pattern="Solid"/>
  </Style>
 </Styles>
 <Worksheet ss:Name="Sheet1">
......

在哪里可以找到我在示例中使用的不同颜色的代码。 希望它对你有用,即使它不是 win32com。

我自己也在玩这个,我找到了一个适用于 win32com 的答案

我使用 myRange._print_details_() 来显示可从 com 对象访问的内容,我得到以下内容:

Methods:
     GetValue
     SetValue
Props:
Get Props:
    Value = 0x6 - <win32com.client.build.MapEntry object at 0x00000184975AA160>
Put Props:
    Value = 0x6 - <win32com.client.build.MapEntry object at 0x00000184975AA1D0>

所以据我所知,Value 是一个允许您使用 myRange.value

获取或设置值的属性

但是还有一个GetValue和SetValue...

所以您要使用 myRange.Value(11).. 而不是

myRange.GetValue(11) # you can now pass the paramter to get xlRangeValueXMLSpreadsheet