use python to Loop through excel worksheets for a range - openpyxl

Hi I am writing code to loop through all the excel spreadsheet in a workbook to pick up a certain range from each spreadsheet.
My code is as below:
from openpyxl import load_workbook
import pandas as pd
wb = load_workbook('D:\Temp\DD_Catalogues_6092020.xlsx')
sheetnames=wb.sheetnames'
for i in sheetnames:
i = wb[i]
row=i.max_row-3
data_rows = []
for row in i[1:row]:
data_cols = []
for cell in row:
data_cols.append(cell.value)
data_rows.append(data_cols)
df = pd.DataFrame(data_rows)
print(df)
However, it doesn't seem loop through all the worksheet and only pick up the first worksheet. May I know how to resolve that? Thank you so much!

Related

Openpyxl - how to create sequential sheets with names

I have a list = ['A17','A18','P08','P09','P10','C03'], and wanted to create worksheets in the workbook and assign worksheets to ws variable:
for i in list:
ws = wb(i)
but how do I get to ws1 = wb['A17'], ws2 = wb['A18'], etc.
Thanks
You can create a worksheet with the following syntax wb.create_sheet(title='test'). It will return the worksheet.
If you want to create sheets using a list, then simply call a for each loop. [wb.create_sheet(title=x) for x in list]. This will return an array of worksheets.
For example:
from openpyxl import Workbook
list = ['A17','A18','P08','P09','P10','C03']
wb = Workbook()
workskheets = [wb.create_sheet(title=x) for x in list]
wb.save("output.xlsx")

Excel VBA - Copy/Paste range from one sheet to all proceeding sheets

First time asking a question so please let me know if I'm missing anything.
I found this code from another SO post. I'm trying to copy the entire worksheet from "DNU" into each proceeding worksheet. The issue I'm having is that this will paste values but I'm looking to do a regular paste to keep the formatting and formulas. I've tried changing from the "Value" to Copy and Paste but this end up in an error. Any help is appreciated. Thank you.
Here is the code:
~
Dim wsVar As Worksheet
Dim i as Integer
For i = 6 to ThisWorkbook.Worksheets.Count
ThisWorkbook.Worksheets(i).Range("A1:y200").Value = ThisWorkbook.Worksheets("DNU").Range("A1:Y200").Value
Next i
End Sub
Use Copy() method of Range object
Dim wsVar As Worksheet
Dim i as Integer
With ThisWorkbook
For i = 6 to .Worksheets.Count
.Worksheets("DNU").Range("A1:Y200").Copy destination:=.Worksheets(i).Range("A1:Y200")
Next
End With

VBA opening two worksheets importing different data in each

Hi im new to VBA excel and i want to import data this part i can do fine but in the same sub i want to open a new worksheet in the same workbook and in that worksheet i want to keep the file names of the data i imported from.
Sub GetData()
Dim path As Variant
Dim excelfile As Variant
Dim data_file(1 To 100) As String
path = "C:\dummmy\"`
main_file = ActiveWorkbook.Name
excelfile = Dir(path & "*.xls")
Do While excelfile <> ""
data_file(k + 1) = excelfile
With ThisWorkbook
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "Test"
ActiveSheet.Paste = datafile(k+1)
End With'
rest of the code the problem i have having is just putting the address of the file in a different worksheet
If I understand your question correctly, you want to know how to work with different worksheets within the same Sub?
That's rather straight forward. Instead of using "ActiveSheet" or anything of the sort, just use their qualified equivalents.
Example:
ThisWorkbook.Worksheets("Data").[...]
ThisWorkbook.Worksheets("Filenames").[...]
This syntax will enable you to operate on specific worksheets. You can either use their name (in my example "Data" and "Filenames") or their position (0, 1, 2 , 3, ...) with 0 being the leftmost worksheet.
When using this syntax it won't matter which worksheet is active, you can do operations on all available worksheets.

vb.net fill combobox using named ranges (excel)

I'm trying to get my application to read a excel file that works with named ranges.
My excel has alot of named ranges, and I would like to access the values in these named ranges to fill my combobox on my windows-user-form.
But i have no idea how get these values.
For now i have this to access my excel spreadsheet + range
Dim excel As Application = New Application
Dim w As Workbook = excel.Workbooks.Open("C:\temp\test.xlsm")
Dim rng As Range
rng = w.Worksheets("Sheet1").Range("range")
w.Close()
On this "Sheet1" there is a Named Range called "Range" and it contains 6 cells. I want to add these cell values to my combobox1 using the Named Range.
But i can't figure out a way to do this.. Can someone help me? :)
You can try using Goto and Selection. Here is a sample that returns an array of values, as per your requirement:
Dim xl As Excel.Application
Dim wb As Excel.Workbook
xl = New Excel.Application
wb = xl.Workbooks.Open("C:\Temp\range.xlsm")
xl.Goto("NewNamedRange")
Dim rng As Excel.Range = xl.Selection
Debug.Print(rng.Value.ToString)

Powerpoint VBA: How to get last used column in a row from an Excel sheet

Q: How do I get the last used column in a specific row from an Excel sheet.
While this is a simple task using Excel VBA its more difficult using Powerpoint VBA.
Here is an example of my Excel sheet
Steps to reproduce
create & save a new Excel sheet like my example above
open a new PowerPoint presentation & hit ALT+F11 for the VBA editor
insert the code below and customize the path to your test Excel file in line 3
execute the code line per line using F8
Sub findlastcolumn()
Set objExcel = CreateObject("Excel.application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\<USERNAME>\Desktop\data.xls")
objExcel.Visible = True
'works in Powerpoint VBA but delivers the wrong column
lastcol = objWorkbook.Sheets(1).UsedRange.Columns.Count
'produces an error in Powerpoint VBA
'but works in Excel VBA, correct column in Excel VBA
lastcol = objWorkbook.Sheets(1).Cells(1, 254).End(Direction:=xlToLeft).Column
'produces an error in Powerpoint VBA
'but works in Excel VBA, and wrong column in Excel VBA too
lastcol = objWorkbook.Sheets(1).Cells.SpecialCells(xlLastCell).Column
'wrong column. Powerpoint VBA' find method differs from Excel' find method
'searchdirection isn't available in Powerpoint VBA
lastcol = objWorkbook.Sheets(1).Rows(1).Find(what:="*", _
after:=objWorkbook.Sheets(1).Cells(1, 1), searchdirection:=xlPrevious).Column
objExcel.Quit
Set objWorkbook = Nothing
Set objExcel = Nothing
End Sub
Desired result: I want to get lastcol = 3
The comments in my code show you what I have tried so far and what error they produce.
I'm thankful for any advice.
There is no PowerPoint 2003 tag? O.o
The Excel specific code you posted should actually work and give you the same result as if you execute it in Excel.
The reason you do get error message is most likely that you did not in include the Excel reference in your Powerpoint VBA! You do use Late Binding, so it's generally not necessary to reference this library. However, the VBA compiler does not know the internal values of the Excel constants/enums xlToLeft, xlLastCell and xlPrevious and therefore produces the error!
Two options to solve your issue:
Include the Microsoft Excel library in your references
Instead of using the Excel specific conmstants/enums, just use their underlying numerical values. To do so, go to the Excel Visual Basic editor. In the Immediate window (Ctrl-G), type ? xlToLeft - and you'll get the result (in this example -4159). Then replace the name in your Powerpoint VBA with the number and it should work. (For better code readability, I usually leave the name of the constant in a comment in the same line, e.g.
lastcol = objWorkbook.Sheets(1).Cells.SpecialCells(11).Column 'xlLastCell = 11
#nixada, You can do it from POWERPOINT vba:
You need to get to the workbook object: (assuming you have the excel data in slide #1, on chart #1:
Set cht = ActivePresentation.Slides(1).Shapes(1).Chart
Set DataWorkBook = cht.ChartData.Workbook
Then you should get your last blank column using the blank type:
LastCol = DataWorkBook.Sheets(1).Cells.SpecialCells(4).Column -1 'xlCellTypeBlanks = 4
That should give you the desired answer "3"
Note: for the list of types you can refer to XlCellType enumeration (Excel)
EDIT: Using xlCellTypeLastCell ( = 11: The last cell in the used range) will not necessary give you the desired answer as if a cell was used but its content now deleted, it will be considered as used cell in the range.
Here is what you can do. * proviso: untested code. If this doesn't work, tell me in the comments *
Dim r as Range
Dim col = 0
set r = objWorkbook.Sheets(1).Range("A1")
while(** test that r has something in it **)
col = col + 1
set r = r.offset(0, 1)
end
I don't have the setup handy to figure out what the test should be - but that ought to be easy. The point is that this doesn't use constants the Powerpoint VBA doesn't know (like xlDown).
I just want to post the corrected code if anyone stumbles over a similar issue. (Thanks to Peter Albert)
Sub findlastcolumn()
Set objExcel = CreateObject("Excel.application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\<USERNAME>\Desktop\input data.xls")
objExcel.Visible = True
icolumn = 1 'which column should be checked (in sheet 1)
'works
Set r = objWorkbook.Sheets(1).Cells(icolumn, objWorkbook.Sheets(1).Columns.Count)
Do: Set r = r.offset(0, -1)
Loop While r.Value = ""
lastcol1 = r.Column
'works
lastcol2 = objWorkbook.Sheets(1).Cells(icolumn, _
objWorkbook.Sheets(1).Columns.Count).End(Direction:=-4159).Column
'works
lastcol3 = objWorkbook.Sheets(1).Rows(icolumn).Find(what:="*", _
after:=objWorkbook.Sheets(1).Cells(1, 1), searchdirection:=2).Column
'works - but not if your columns have different last cells
lastcol4 = objWorkbook.Sheets(1).UsedRange.Columns.Count
'works - but not if your columns have different last cells
lastcol5 = objWorkbook.Sheets(1).Cells.SpecialCells(11).Column
End Sub