Mark Barry
Mark Barry

Reputation: 49

I am trying to copy/paste a named Excel range to another range in the same worksheet using Python xlwings

I am trying to copy a named range in Excel (ex. "Question_1") and paste it into an empty area of the same worksheet, using Python (xlwings). I am getting an attribute error which mentions "api". The last 1 or 2 lines of the code appear to be the problem.

The spreadsheet internally contains a set of multiple choice questions and each question draws on a set of incorrect responses and correct responses which are jumbled each time the spreadsheet refreshes. The Python code is to create a random selection of questions out of the total which will eventually reach 50.

I am using Spyder.

import xlwings as xw
mypath= "C:\\Users\\barry\\Desktop\\WS Generators\\MC Question Generator2.xlsm"
app= xw.App()
wb=app.books.open(mypath)
sheet = wb.sheets["Sheet1"]

import random
randomnumber = random.randint(1,15)
randlist = []
randlist.append(randomnumber)

for i in range(5):
    randomnumber = random.randint(1,15)
    if randomnumber in randlist:
        continue
    else:
        randlist.append(random.randint(1,15))

j=0
question = "Question_"+str(randlist[j])
print(question)
sheet["question"].select
sheet["question"].copy("K2:M9")
sheet.range("K2:M9").paste(None,None,False,False)

The last block of code, starting with j = 0, is going to be a loop through the elements of randlist. First, I needed to tackle the copy/paste issue. I've searched all over but to no avail. Thanks in advance.

Upvotes: 0

Views: 55

Answers (0)

Related Questions