Copying range from one excel workbook to another

Question:

I am trying to copy a range form one excel sheet to another.
This is my code:

import openpyxl
import os

#Current path
path = os.path.dirname(os.path.abspath(__file__))

#Beregningsmodul navn
Beregningsmodul_moder = "Beregning COREP LCR - MODER - 202202.xlsx"

#Skema 72 navn
workbook_skema_72 ="C_72_00_a.xlsx"

#workbook_beregn path
workbook_beregn_path = path + "\" + Beregningsmodul_moder
workbook_beregn = openpyxl.load_workbook(workbook_beregn_path)

#Kopier til
wb_72C = workbook_beregn["72C"]['E8':'G54']

#kopier fra
C_72_00_a = workbook_skema_72["C_72_00_a"]['D9':'F55']

#Pair the rows
for row1,row2 in zip(C_72_00_a, workbook_beregn):
    #within the row pair, pair the cells
    for cell1, cell2 in zip(row1,row2):
        #assign the value of cell 1 to the destination cell 2 for each row
        cell2.value = cell1.value
#save document
workbook_beregn.save('destination.xlsx')

But I get this error:

C_72_00_a = workbook_skema_72["C_72_00_a"]['D9':'F55']
TypeError: string indices must be integers

Am I defining the ranges in a wrong way or something?
I hope you can point me in the right direction.

Asked By: Christoffer

||

Answers:

My best solution was to use VBA code to solve the issue I hope this can help someone in the future:

Sub HentData()

'Improves performance / stability
Call OptimizeCode_Begin

Dim Time As Variant

'Monitor duration of runtime
StartDateTime = Now

Dim tws As Worksheet
Dim Path As String
Dim Files As String
Dim wb As Workbook

Set twb = ThisWorkbook
Set tws = twb.Worksheets("Currentpath")
Path = tws.Range("Path_Skema").Value
Files = Dir(Path & "*.xlsx")

'----------------
While Files <> ""
'----------------

        'Skema 72
        '--------------------------
        If Files Like "*C_72*" Then
        '--------------------------
        
            'ClearContents sheet "72C"
            Windows("Beregning COREP LCR - MODER.xlsm").Activate
                Sheets("72C").Select
                ActiveSheet.AutoFilterMode = False
                Cells.Select
                Selection.Clear
                Range("A1").Select
            
            'Open workbook "C_72_00_a.xlsx"
            Set wb = Workbooks.Open(Path & "" & Files)
            
            'Copy content
            Windows(Files).Activate
                ActiveSheet.Select
                Cells.Select
                Selection.Copy
                
            'Paste content
            Windows("Beregning COREP LCR - MODER.xlsm").Activate
                Sheets("72C").Select
                Range("A1").Select
                Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
                , SkipBlanks:=False, Transpose:=False
                Application.CutCopyMode = False
                
                'Format content
                Cells.Select
                Cells.EntireColumn.AutoFit
                Range("A1").Select
            
            'Close - C_72_00_a.xlsx
            Windows(Files).Activate
                Application.DisplayAlerts = False
                ActiveWindow.Close SaveChanges:=False
                Application.DisplayAlerts = True
            
            'Checks file timestamp
            Windows("Beregning COREP LCR - MODER.xlsm").Activate
                Sheets("Opdater_Skema").Select
                Time = Format(FileDateTime(Path & "" & Files), "mm-dd-yyyy hh:mm")
                Range("Date_C_72_00_a").Value = Time
            
        End If
        
        'Skema 73
        '--------------------------
        If Files Like "*C_73*" Then
        '--------------------------
        
            'ClearContents sheet "73C"
            Windows("Beregning COREP LCR - MODER.xlsm").Activate
                Sheets("73C").Select
                ActiveSheet.AutoFilterMode = False
                Cells.Select
                Selection.Clear
                Range("A1").Select
            
            'Open workbook "C_73_00_a.xlsx"
            Set wb = Workbooks.Open(Path & "" & Files)
            
            'Copy content
            Windows(Files).Activate
                ActiveSheet.Select
                Cells.Select
                Selection.Copy
                
            'Paste content
            Windows("Beregning COREP LCR - MODER.xlsm").Activate
                Sheets("73C").Select
                Range("A1").Select
                Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
                , SkipBlanks:=False, Transpose:=False
                Application.CutCopyMode = False
                
                'Format content
                Cells.Select
                Cells.EntireColumn.AutoFit
                Range("A1").Select
            
            'Close - C_73_00_a.xlsx
            Windows(Files).Activate
                Application.DisplayAlerts = False
                ActiveWindow.Close SaveChanges:=False
                Application.DisplayAlerts = True
            
            'Checks file timestamp
            Windows("Beregning COREP LCR - MODER.xlsm").Activate
                Sheets("Opdater_Skema").Select
                Time = Format(FileDateTime(Path & "" & Files), "mm-dd-yyyy hh:mm")
                Range("Date_C_73_00_a").Value = Time
        
        End If
        
        'Skema 74
        '--------------------------
        If Files Like "*C_74*" Then
        '--------------------------
            'ClearContents sheet "74C"
                Windows("Beregning COREP LCR - MODER.xlsm").Activate
                    Sheets("74C").Select
                    ActiveSheet.AutoFilterMode = False
                    Cells.Select
                    Selection.Clear
                    Range("A1").Select
                
                'Open workbook "C_74_00_a.xlsx"
                Set wb = Workbooks.Open(Path & "" & Files)
                
                'Copy content
                Windows(Files).Activate
                    ActiveSheet.Select
                    Cells.Select
                    Selection.Copy
                    
                'Paste content
                Windows("Beregning COREP LCR - MODER.xlsm").Activate
                    Sheets("74C").Select
                    Range("A1").Select
                    Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
                    , SkipBlanks:=False, Transpose:=False
                    Application.CutCopyMode = False
                    
                    'Format content
                    Cells.Select
                    Cells.EntireColumn.AutoFit
                    Range("A1").Select
                
                'Close - C_74_00_a.xlsx
                Windows(Files).Activate
                    Application.DisplayAlerts = False
                    ActiveWindow.Close SaveChanges:=False
                    Application.DisplayAlerts = True
                
                'Checks file timestamp
                Windows("Beregning COREP LCR - MODER.xlsm").Activate
                    Sheets("Opdater_Skema").Select
                    Time = Format(FileDateTime(Path & "" & Files), "mm-dd-yyyy hh:mm")
                    Range("Date_C_74_00_a").Value = Time
        End If
        
        'Skema 76
        If Files Like "*C_76*" Then
        'ClearContents sheet "76C"
                Windows("Beregning COREP LCR - MODER.xlsm").Activate
                    Sheets("76C").Select
                    ActiveSheet.AutoFilterMode = False
                    Cells.Select
                    Selection.Clear
                    Range("A1").Select
                
                'Open workbook "C_76_00_a.xlsx"
                Set wb = Workbooks.Open(Path & "" & Files)
                
                'Copy content
                Windows(Files).Activate
                    ActiveSheet.Select
                    Cells.Select
                    Selection.Copy
                    
                'Paste content
                Windows("Beregning COREP LCR - MODER.xlsm").Activate
                    Sheets("76C").Select
                    Range("A1").Select
                    Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone _
                    , SkipBlanks:=False, Transpose:=False
                    Application.CutCopyMode = False
                    
                    'Format content
                    Cells.Select
                    Cells.EntireColumn.AutoFit
                    Range("A1").Select
                
                'Close - C_76_00_a.xlsx
                Windows(Files).Activate
                    Application.DisplayAlerts = False
                    ActiveWindow.Close SaveChanges:=False
                    Application.DisplayAlerts = True
                
                'Checks file timestamp
                Windows("Beregning COREP LCR - MODER.xlsm").Activate
                    Sheets("Opdater_Skema").Select
                    Time = Format(FileDateTime(Path & "" & Files), "mm-dd-yyyy hh:mm")
                    Range("Date_C_76_00_a").Value = Time
        End If
    
    'Set variable to next file
    Files = Dir()

Wend

'---------
Windows("Beregning COREP LCR - MODER.xlsm").Activate
    Sheets("Opdater_Skema").Select
    Range("Opd.HentData") = Now
    Range("Opd.HentData").Select

'Monitor duration of runtime
EndDateTime = Now

'Duration of current run
Duration = Format(EndDateTime - StartDateTime, "hh:mm:ss")
Range("var_hentdata").Value = Duration

'ActiveWorkbook.Save

'Improves performance/stability
Call OptimizeCode_End

End Sub
Sub OptimizeCode_Begin()

Application.ScreenUpdating = False
ActiveSheet.DisplayPageBreaks = False
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.DisplayStatusBar = False
'Application.Calculation = xlCalculationManual

End Sub


Sub OptimizeCode_End()

Application.ScreenUpdating = True
ActiveSheet.DisplayPageBreaks = True
Application.EnableEvents = True
Application.DisplayAlerts = True
Application.DisplayStatusBar = True
Application.Calculation = xlCalculationAutomatic

End Sub

I attach this code to a button in excel and then the other sheets are copied in to the sheet.

The following variables are found by functions in excel:
enter image description here

Path: =LEFT(CELL("filename";$B$1);FIND("[";CELL("filename";$B$1);1)-1)

Skema_path:

=SUBSTITUTE(B2;"Intradag likviditet";"LCR skema")
Answered By: Christoffer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.