xlswriter: how to copy an existing sheet - xlsxwriter

I have a sample excel doc. Two sheets of this doc contain a long description of the doc, I am writing a script to generate some dynamic excel data , I will need add these two static page into my result. What is the best way? I can only think of creating a long data list, then do a add_table. But the text is quite large and big, wonder if there is any better way.

If the long descriptions are static then you could store them in text files and add them to each workbook like this:
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet('Desc 1')
textfile = open('description_1.txt')
# Write the first description worksheet.
row = col = 0
for line in textfile:
worksheet.write(row, col, line.rstrip("\n"))
row += 1
worksheet = workbook.add_worksheet('Desc 2')
textfile = open('description_2.txt')
# Write the second description worksheet.
row = col = 0
for line in textfile:
worksheet.write(row, col, line.rstrip("\n"))
row += 1
# Now add a new worksheet and add new data.
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Hello')
workbook.close()
The repeated code could be put into a function. If you are reading non ASCII text then use the correct encoding. See the examples in the docs.

Related

PowerPoint/Excel VBA - Change default range of data for a chart

I want to be able to use my own Excel Workbook to create a pie diagram in PowerPoint. So far, I have created a VBA script to add the chart. I also changed the data sheet for the chart to look like this:
Problem
Following core problem remains:
I can't figure out, how to dynamically define the data range of the chart's data source sheet
Because the default values for the pie chart belong to these ranges, PowerPoint sets those ranges by default. If my data sheet contains more (or equal to) than 4 rows of data, it won't be that bad, as the range automatically increases. However, as shown in the example, the range doesn't adapt when there are only 3 rows of data.
What I want, would look like this: Needed (I only know how to get the data in the correct place, but not how to select it)
Related VBA code is below:
Set diaPie = pres.Slides(3).Shapes.AddChart2(2, xlPie).Chart
Set pieChartData = diaPie.ChartData
Set pieWorkbook = pieChartData.Workbook
Set pieWorksheet = pieWorkbook.Worksheets(1)
pieWorksheet.UsedRange.Clear
With dataWorksheet
id = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
a = dataWorksheet.Range("A1", dataWorksheet.Range("A1").Offset(id, 0))
b = dataWorksheet.Range("B1", dataWorksheet.Range("B1").Offset(id, 0))
pieWorksheet.Range("A2", pieWorksheet.Range("A2").Offset(id, 0)) = a
pieWorksheet.Range("B2", pieWorksheet.Range("B2").Offset(id, 0)) = b
Thanks in advance!
This should change the data range on your data sheet. maxrow is just the end of the data. So if your data is in B1:B4 then maxrow would be 4
diaPie.SeriesCollection(1).values = "Sheet1!$B$1:$B" & maxrow ' change the series range before opening and closing the workbook object
diaPie.SeriesCollection(1).XValues = "Sheet1!$A$1:$A" & maxrow 'Labels

Excel Change Columns Based On Another One

I'm currently working on 6 Excel workbooks all with same format. Basicly i have a table which includes product codes with their amount needs to be used. I have around 200 worksheets in every Excel file with same format. I want to update these product amount based on multiplier table i made. Here an example of data below;
Sample of data
Multiplier table
So the new values of sample codes should be 4,15 3,5 7,84 and 88,62.
Because the high amount of pages with workbooks, probably changing or inserting some kind of formula one by one would take very long time. I wonder how can I get the job done with few easy steps.
Thanks!
All you need to do is to use VLookup function or array formula. Then you'll be able to fill down or copy formula for every single record.
In your case i'd suggest to use array formula. Assuming, if MultiplierTable is the name of worksheet and that worksheet contains data (as you provided) in a range C4:D7, you can copy below formula and paste it into E4 cell:
=D4*SUM(IF(C4=MultiplierTable!C$4:C$7,MultiplierTable!D$4:D$7,0))
Fill down the formula. Select entire column and paste as values in the same column. Repeat this step for each worksheet.
Follow the links for further details.
In case, you want to use VBA, please let me know. I'll try to improve my answer.
I checked some guides for basics of VBA and created my own VBA script. It became a little hardcoded but because this is one time job, it get the job done.
Sub degistir()
Dim WS_Count As Integer
Dim I As Integer
Dim val As Double
WS_Count = ActiveWorkbook.Worksheets.Count
For I = 1 To WS_Count
Worksheets(I).Activate
For R = 8 To 14
val = ActiveSheet.Cells(R, 4)
If ActiveSheet.Cells(R, 2) Like "P001" Then
val = val * 1
ElseIf ActiveSheet.Cells(R, 2) Like "P002" Then
val = val * 0.533333333
'and goes...
End If
ActiveSheet.Cells(R, 4).Value = val
Next R
Next I
End Sub

Excel Rows (1st column) as .php files + Excel Row 1 (2nd column to infinty) as data of all files

I found relevent things but not the exact match and I don't know how fix them.
I have an excel file with only 1 row(with many columns) and 1 column (with many rows).
Now I would like to use vba and create files from all the rows of 1st column and , put the same data (i.e. cloumn b to infinty of 1st row) inside all the files.
Just an example:
excel file:
a 2 3 4
b
c
files would be:
a.php, b.php, c.php
with same data inside them:
2 3 4
Thanks in advance
While the rationale for doing this to generate web content eludes me, this is trivial to do. Just loop through the 1st row to get the data, then loop through the first column to get the filenames and output copies:
Const path = "C:\YourDestinationDirectory\"
Public Sub DumpPHP()
Dim sheet As Worksheet
Dim data As String
Dim index As Long
Set sheet = ActiveSheet
For index = 2 To sheet.UsedRange.Columns.Count
data = data & sheet.Cells(1, index)
Next index
Dim handle As Integer
For index = 2 To sheet.UsedRange.Rows.Count
handle = FreeFile
Open path & sheet.Cells(index, 1) & ".php" For Output As #handle
Print #handle, data
Close #handle
Next index
End Sub

Save Word document as a filename generated from tabled info contained within the document

I am looking to enable Word to save with a file name using data contained within the document.
At the top of the document (an airline release letter), there is a table containing 2 columns with 3 rows containing alpha in one column and alpha-numeric data in column 2.
Column 1,
Cell 1: AETC; Cell 2: MAWB; Cell 3: HAWB
Column 2,
Cell 1: 80123; Cell 2, 0161234567; Cell 3: 00112345678
Basically, the first column will be the static labels for the variable data to be entered into column 2.
From all this, I want to generate a save-as file name: AETC80123_MAWB0161234567_HAWB00112345678_ReleaseLetter.doc
I've barely scratched the surface of VBA as I am more an operations supervisor than a techie so I'm not certain if this is even possible.
Any help/direction/copy-paste coding (if it's super easy and of little trouble) would be awesome!
Thanks!
I am not going to work it all out in detail for, nor is this tested at all (just written out of my head), but this should give a hint how you read cell content in a Word document:
' Set tbl to first table in document
Dim tbl As Table
Set tbl = ActiveDocument.Tables(0)
Dim r As Integer
Dim c As Integer
Dim val As String
Dim filename As String
filename = ""
For r = 1 To tbl.Rows.Count
For c = 1 To tbl.Columns.Count
' Get text in cell
val = tbl.Cell(r, c).Range.Text
' and append to string or whatever
filename = filename & val & "_"
Next c
Next r
Finally, save your document using
ActiveDocument.SaveAs FileName:=filename
Check this microsoft site for more information about SaveAs parameters.

Copying Row Info from one sheet to another based on match

I have an excel book that has two sheets: 1) Import 2) Pricing Rules.
Pricing Rules Sheet
The A column is what I need to match on. Example values include STA_PNP4, STA_PST.. and others. There are potentially around 50 different rows in the sheet, and it will continue to grow over time. Then for each row, there are pricing values in columns B to CF.
Import Sheet
This sheet has the same number of columns, but only Column A is filled out. Example values include STA_PNP4_001_00, STA_PNP4_007_00, STA_PST_010_00.. and many more.
What I need to do:
If the text in Import Sheet Column A before the second "_" matches the column identifer in Pricing Rules Sheet Column A, copy the rest of B to CF of Pricing Rules sheet for that row into the Import sheet for the row it matched on.
Any idea on where to begin with this one?
Why don't you do it using formulas only?
Assuming :
1.) Data in Import Sheet is
(col A)
STA_PNP4_007_00
STA_PNP4_001_00
STA_PNP4_001_00
.
.
2.) Data in Pricing Rules Sheet
(Col A) (col B) (ColC) (Col D) .......
STA_PNP4 1 2 3 .....
STA_PST 4 5 6 .....
STA_ASA2 7 8 9 .....
Then write this formula in B1 cell of Import Sheet
=IFERROR(VLOOKUP(LEFT(A1,FIND("",A1,FIND("",A1)+1)-1),PricingRules!$A$1:$CF$100,2,0),"")
Drag it down in column B
and For Column C , D just change index num from 2 to (3 for C) , (4 for D) and like that.
Because it will continue to grow over time you may be best using VBA. However, even with code I would start by applying the ‘groups’ via formula, so as not to have a spreadsheet overburdened with formulae and hence potentially slow and easy to corrupt. Something like part of #xtremeExcel’s solution which I repeat because the underscores have been treated as formatting commands in that answer:
=LEFT(A1,FIND("_",A1,1+FIND("_",A1))-1)
I’d envisage this (copied down) as an additional column in your Import Sheet - to serve as a key field to link to your Pricing Rules Sheet. Say on the extreme left so available for use by VLOOKUP across the entire sheet.
With that as a key field then either:
Write the code to populate Pricing Rules Sheet as frequently as run/desired. Either populating ‘from scratch’ each time (perhaps best for low volumes) or incrementally (likely advisable for high volumes).
Use VLOOKUP (as suggested). However with at least 84 columns and, presumably, many more than 50 rows that is a lot of formulae, though may be viable as a temporary ‘once off’ solution (ie after population Copy/Paste Special/Values).
A compromise. As 2. But preserve a row or a cell with the appropriate formulae/a and copy that to populate the other columns for your additions to your ColumnA and/or ColumnA:B.
Thanks for the input guys.
I got it implemented via a method like this:
{=VLOOKUP(LEFT($A4,7),PricingRules!A3:CF112,{2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84},FALSE)}
That is my ugly function, applied across a whole row, to look up and copy from my pricing rules every column when it finds a match.
Below is the function that I have created for above scenario. Its working as per the requirement that you have mentioned.
Sub CopyData()
Dim wb As Workbook
Dim importws As Worksheet
Dim PricingRulesws As Worksheet
Dim Pricingrowcount As Integer
Dim importRowCount As Integer
Dim FindValue As String
Dim textvalue As String
Dim columncount As Integer
Dim stringarray() As String
'Enter full address of your file ex: "C:\newfolder\datafile.xlsx"
Set wb = Workbooks.Open("C:\newfolder\datafile.xlsx")
'Enter the name of your "import" sheet
Set importws = Sheets("Import")
'Enter the name of your "Pricing" sheet
Set PricingRulesws = Sheets("PricingRules")
For Pricingrowcount = 1 To PricingRulesws.UsedRange.Rows.Count
FindValue = PricingRulesws.Cells(Pricingrowcount, 1)
For importRowCount = 1 To importws.UsedRange.Rows.Count
textvalue = importws.Cells(importRowCount, 1)
stringarray = Split(textvalue, "_")
textvalue = stringarray(0) & "_" & stringarray(1)
If FindValue = textvalue Then
For columncount = 2 To PricingRulesws.UsedRange.Columns.Count
importws.Cells(importRowCount, columncount) = PricingRulesws.Cells(Pricingrowcount, columncount)
Next columncount
End If
Next importRowCount
Next Pricingrowcount
End Sub