An experienced VBA programmer here, that is starting the delve into Python OOP. I fear it is so simple, that I am having issues finding an answer without asking for help.
I have written the following code:
#Import packages
import openpyxl as xl
import os
class DataExtract:
#Initialize the class
def __init__(self,wb):
self.wb = wb
#Set class method to return sheet for named range
@classmethod
def rng_sht(cls,dest):
for title, coord in dest:
return(title)
#Set class method to return cell for named range
@classmethod
def rng_coord(cls,dest):
for title, coord in dest:
return(coord)
#Set class method to retun value of named range
@classmethod
def rng_val(cls,rng):
#Define destinations
dest = wb.get_named_range(rng).destinations
#Retrieve sheet
sht = DataExtract.rng_sht(dest)
coord = DataExtract.rng_coord(dest)
#Return value
return()
#Define workbook
wb = 'Test_WB'
#Initiate class
wb_cur = DataExtract(wb)
#Find temp for current sheet
Temp = wb_cur.rng_val('Temp')
I'm aware that my indentation is incorrect.
The issue that I am having is that when I call the rng_val class method, it is only returning the current value for the first method I call within (in this case, the "sht"). When I inactivate the "sht" line, the "coord" line functions correctly.
I suspect the issue is likely due to how I am calling class methods or how I have structured the class, but I am not sure.
Update
I have updated the code with feedback from all of you, with my script below. I am still having errors with exiting the loop in the rng_val class, which Max suggested yield
to resolve. I attempted to fix to no avail.
#Import packages
import openpyxl as xl
import os
class DataExtract:
#Initialize the class
def __init__(self,wb):
self.wb = wb
#Set class method to return sheet for named range
@classmethod
def rng_sht(cls,dest):
for title, coord in dest:
return title
#Set class method to return cell for named range
@classmethod
def rng_coord(cls,dest):
for title, coord in dest:
return coord
#Set class method to retun value of named range
@classmethod
def rng_val(cls,wb,rng):
#Define destinations
dest = wb.get_named_range(rng).destinations
#Retrieve sheet
sht = cls.rng_sht(dest)
coord = cls.rng_coord(dest)
print(sht)
print(coord)
#Return value
return 1
path = 'C:\\Users\\User\\Desktop\\Python\\PracFiles\\'
#Loop through workbooks in a given folder
for i in os.listdir(path):
#Define workbook
wb = xl.load_workbook(path + i,data_only=True)
#Find temp for current sheet
Temp = DataExtract.rng_val(wb,'Temp')