简体   繁体   中英

python Win32 Excel is cell a range

I am writing a bit of Python code to automate the manipulation of Excel spreadsheets. The idea is to use spreadsheet templates to create daily reports. Saw this idea working several years ago using Perl. Anyway.

Here are the simple rules: Sheets with the Workbook are process in the order they appear. Within the sheets cells are process left to right, then top to bottom. There are names defined which are single cell ranges, can contain static values or the results of queries. Cells can contain comments which contain SQL queries to run. ...

Here is the problem, as I process the cells I need to check if the cell has an attached comment and if the cell has a name. I am able to handle processing the attached cell comments. But I can not figure out how to determine if a cell is within a named range. In my case the single cell within the range.

I saw a posting the suggested this would work: cellName = ws.ActiveCell.Name.Name No luck.

Does anybody have any idea how to do this? I am so close but no cigar.

Thanks for your attention to this matter.

KD

OK so it errors out if the cell does NOT have a range name. If the cell has a range name the following bit of code returns the name: Great success!!

ws.Cells(r,c).Activate()
c  = xlApp.ActiveCell
cellName = c.Name.Name 

If there is no name associated with the cell, an exception is tossed.
So even in VBA you would have to wrap this bit of code in exception code. Sounds expensive to me to use exception processing for this call.

What you may consider doing is first building a list of all addresses of names in the worksheet, and checking the address of each cell against the list to see if it's named.

In VBA, you obtain the names collection (all the names in a workbook) this way:

Set ns = ActiveWorkbook.Names

You can determine if the names are pointed toward part of the current sheet, and a single cell, this way:

shname = ActiveSheet.Name
Dim SheetNamedCellAddresses(1 To wb.Names.Count) as String
i = 1
For Each n in ns:
If Split(n.Value, "!")(0) = "=" & shname  And InStr(n.Value, ":") = 0 Then
' The name Value is something like "=Sheet1!A1"
' If there is no colon, it is a single cell, not a range of cells
SheetNamedCellAddresses(i) = Split(n,"=")(1) 'Add the address to your array, remove the "="
i = i + 1
End If
Next

So now you have a string array containing the addresses of all the named cells in your current sheet. Move that array into a python list and you are good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM