Openpyxl - how to create sequential sheets with names - openpyxl

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")

Related

MS Access VBA: Creating Excel Workbook with multiple Worksheets

I can create a workbook that contains a single worksheet using the following code:
'Create Custom Excel Report
Set XL = New Excel.Application
XL.Visible = True
Set WB = XL.Workbooks.Add
Set WKS = WB.Worksheets(1)
WKS.Name = "Fred"
'Set Report Headers
WKS.Cells(2, 1).value = "Name"
WKS.Cells(2, 2).value = "Address"
WKS.Cells(2, 3).value = "Hat Size"
How can I create a workbook that has 3 worksheets? How do I set the values for the individual worksheets?
The workbook starts with one sheet. You can append a sheet and name it via a line like this:
WB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = "Fred"
You can assign a variable on creation, or you can reference the new sheet be name: E.g., WB.Sheets("Fred")

Referencing data from another workbook in an array

I am currently using the below code to define an array from the active workbook
Dim MyRangeArray As Variant
MyRangeArray = Array(Sheet1.Range("A4:N19"), Sheet2.Range("A4:N19"))
I want this array to reference data from another workbook instead of the workbook which has the code. The result i am looking for is:
MyRangeArray= Array(Wb1.sheets.RangeX,wb2.sheets.rangeX)
Can somebody help?
In your first example you are using sheet Code Names, which will reference sheets in the book containing the code, irrespective of if that book is active.
To reference a different workbook, again irrespective of if it's active, create references to the workbook and worksheet objects
Dim MyRangeArray As Variant
Dim wb As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Set wb = Application.Workbooks("NameOfWorkbook.xlsx")
Set ws1 = wb.Worksheets("NameOfSheet1")
Set ws2 = wb.Worksheets("NameOfSheet2")
MyRangeArray = Array(ws1.Range("RangeAddress1").Value, ws2.Range("RangeAddress2").Value)
I resolved the error by doing the following:
Dim r1,r2 as range
r1=ws1.Range("RangeAddress1")
r2=ws2.Range("RangeAddress2")
Mrangearray=array(r1,r2)

Copy paste worksheet 'name' only

I need to copy paste all my Worksheet name in the current workbook to a new workbook with same worksheet names. (without the datas. I only need the worksheet names.)
I tried following VBA but it shows the error
"The name is already taken." (Runtime Error 1004)
'Create new work book for Pivot
Dim Source As Workbook
Dim Pivot As Workbook
Set Source = ActiveWorkbook
Set Pivot = Workbooks.Add
Dim ws As Worksheet
For Each ws In Worksheets
'Create new worksheet in new excel
Dim Line As String
Line = ActiveSheet.Name
Pivot.Activate
Sheets.Add
ActiveSheet.Name = Line
Source.Activate
Next
You never use ws so Line never changes. Also you do not need to select or activate anything. Finally, you should qualify your Worksheets etc with the workbook they come from.
Dim Source As Workbook
Dim Pivot As Workbook
Set Source = ActiveWorkbook
Set Pivot = Workbooks.Add
Dim ws As Worksheet
For Each ws In Source.Worksheets
Pivot.Worksheets.Add.Name = ws.Name
Next
That will not protect you from a situation where there is already a sheet in the new workbook with the name identical to one of your sheets name (e.g. Sheet1), and it will leave any sheets the new workbook has by default (controlled by the Application.SheetsInNewWorkbook property).

Excel 2010 VBA - Use Value of variable as another variable

This is a practice I follow while writing VBA code.
I usually set worksheet names without spaces into variable names.
For example I have a workbook with 3 worksheets with following names
1 - Control
2 - 60 W Status
3 - 60 W Status Pvt Tbl
I usually set worksheets names as worksheet variables in the following way:
Set wb = thisworkbook
Set wsControl = wb.sheets("Control")
Set ws60WStatus = wb.sheets("60 W Status")
Set ws60WStatusPvtTbl = wb.sheets("60 W Status Pvt Tbl")
Now I want to make this dynamic meaning my code should loop through all the worksheets in a workbook and store the worksheet names without spaces into variable names like ws*
So I have the following code so far:
Sub GetwsNames()
Set wb = thisworkbook
Dim wsNames()
i = 0
'Loop through the workbook and store the names as wsName in an array
For each ws in worksheets
Redim Preserve wsNames(i)
Var1 = ws.Name
Var2 = Replace(ws.Name," ", "")
Var3 = "ws" & Var2
wsNames(i) = Var3
i = i + 1
Next
'Loop through array wsNames() and assign each element to corresponding workbook names
'For example
'Set wsControl = wb.sheets("Control")
'Set ws60WStatus = wb.Sheets("60 W Status")
'Set ws60WStatusPvtTbl = wb.sheets("60 W Status Pvt Tbl")
End Sub
I would like to know if there is any way to achieve this. Can we use value of a variable as another variable?
You can already reference sheets by name from the worksheets collection.
Worksheets("Sheet 1")
If you instead want to reference them by your modified names, creating an array or dictionary will work great. I suggest using a dictionary. It will allow you to reference items by key. In this example I use the modified name as the key and use the worksheet object as the item.
Dim myWorksheets As Scripting.Dictionary
Set myWorksheets = New Scripting.Dictionary
Dim ws As worksheet
For Each ws In ThisWorkbook.Worksheets
Dim modifiedName As String
modifiedName = "ws" & Replace(ws.Name, " ", "")
myWorksheets.Add modifiedName, ws
Next
'You can now reference the worksheets by the modified names, through the dictionary
myWorksheets("wsControl").Cells(1, 1) = "Hi"
myWorksheets("ws60WStatus").Cells(1, 1) = "there"
myWorksheets("ws60WStatusPvtTbl").Cells(1, 1) = "world."
Note that you will need to add a reference to MS Scripting runtime in order to use dictionaries.
To add the reference, go to Tools->References and check its box.

Excel 2007 data collection

aI have an Excel 2007 workbook with about 150+ worksheets and I want to select the data from the same same cell in all worksheets and copy the data (it is all text) from only those cells that contain data; to a separate worksheet with the data listed in a column.
You can use the following VBA:
Dim WriteCell as Range
Set WriteCell = Sheets("New Sheet").Range("A2")
Dim MySheet as Worksheet
For Each MySheet In ThisWorkbook.Worksheets
If MySheet.Range("B2").Value <> "" Then
WriteCell.Value = MySheet.Range("B2").Value
WriteCell.Offset(0, -1).Value = MySheet.Name
Set WriteCell = WriteCell.Offset(1,0)
End If
Next
That's if it's the same worksheet within that workbook. If you want it to be some other workbook, replace the For Each line with this:
Workbooks.Open File:= "C:\MyBook.xlsx"
For Each MySheet in ActiveWorkbook.Worksheets
This will just iterate through all of the worksheets, testing that value, and generating a worksheet with Worksheet Name and Cell Value as columns.