How to copty only the value and not the formula into another workbook ? (openpyxl) - openpyxl

I will not put all my script, for the sake of clarity.
I created a workbook, where I stored data based on an csv files, then I created cells who contains sums of those data :
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
sheet2=wb.create_sheet('somme')
sheet['C16'] = '= SUM(A100:A212)'
sheet['D16'] = '= SUM(B100:B212)'
sheet['E16'] = '= SUM(C100:C212)'
sheet['F16'] = '= SUM(D100:D212)'
But I want the sums to be in another sheet, but not the formula, just the value, because otherwise it will be 0 because in sheet2 there is no data to sum.
I tried this :
for row in sheet['A1':'Z100']:
for cell in row:
sheet2[cell.coordinate].value = cell.value
But it return formula, so I don't have the number, just 0.
Any ideas how to fix that ?

You could do this by having the cells in sheet2 reference the sum cells with a formula, like =Sheet1!C16.
If you already know the title of sheet, you can just use that directly. If not, it's probably a good idea to use openpyxl.utils.cell.quote_sheetname() to avoid potential issues with spaces:
sheet2[cell.coordinate].value = f"={quote_sheetname(sheet.title)}!{cell.coordinate}"
Another approach, if you don't want the sums in the main worksheet, would be to put the sum formulas directly in sheet2, and add the title of the first worksheet to the cell ranges.

Related

Copy rows based on cell value and paste on a new sheet

Check This
I need a help. I want to copy whole cell from A sheet name "Components" only if value in Column C is > 0 to a new Sheet name "Load list"
Can someone please give me the macro code for this?
on your new sheet you can add this condition the cell or range of cells:
=IF(Components!C5>0,Components!A5)
where C5 has thevalue to compare, and A5 has the value copy if the condition happens.
Right in my swing!
The formula given by #sweetkaos will work fine, in case you want to replicate the data as it is with blanks where data is not found.
I will imagine a slightly more complicated situation. I am assuming you want just one line in the next format as is shown in your image.
Also conveniently assuming the following:
a. both sheets have fixed start points for the lists
b. 2 column lists - to be copied and pasted, with second column having value
c. Continuous, without break source list
d. basic knowledge of vba, so you can restructure the code
Here is the code. Do try to understand it line by line. Happy Excelling!
Sub populateLoadList()
'declaring range type variables
Dim rngStartFirstList As Range, rngStartLoadList As Range
'setting values to the range variables
'you must change the names of the sheets and A1 to the correct starts of your two lists
Set rngStartFirstList = Worksheets("Name_of_your_fist_sheet").Range("A1")
Set rngStartLoadList = Worksheets("Name_of_your_second_sheet").Range("A1")
Do While rngStartFirstList.Value <> ""
If rngStartFirstList.Offset(1, 0).Value < 0 Then
Range(rngStartFirstList, rngStartFirstList.Offset(0, 1)).Copy
rngStartLoadList.PasteSpecial xlPasteValues
Application.CutCopyMode = False
Set rngStartLoadList = rngStartLoadList.Offset(1, 0)
End If
Set rngStartFirstList = rngStartFirstList.Offset(1, 0)
Loop
End Sub
Basically what i want is ... if Value on C is >0 i want whole column 10 copied to that new sheet .... not only that cell

Excel : Copy and paste multiple rows and columns from one worksheet to another

i would like to copy multiple rows from one worksheet to another , i have data starting in one worksheet at A2 row and ends at A108850 and it starts at A2 column and ends at I2 column , how can i copy all that data into another worksheet where row starts with A4 and column starts with A4 and ends with I4.
How could i possibly do it through some macro?.
Thanks.
Try this
Worksheets("Sheet1").Range("A2:I108850").Copy Worksheets("Sheet2").Range("A4")
Change the range reference and worksheet's name accordingly.
Copy&Paste is an "expensive" operation, the greater the range the more expensive the operation
Should you be interested in values only, you could try this:
Worksheets("DestinationSheetName").Range("A2:I108850").Value = Worksheets("SourceSheetName").Range("A2:I108850").Value
edited after OP's comment
Should the code in your last comment have the same aim of pasting values only, then change the second statement into the following:
With Worksheets("Sheet1").Range("A2:I108850") '<--| reference the "source" range you want to paste values from
.Range("A4").Resize(.Rows.Count, .Columns.Count).Value = .Value '<--| resize "destination" range accordingly to "source" one and paste values into it
End With
of course you must check for sheet names to be valid ones for the currently active workbook

How can I copy & paste entire rows with distinct values to a new sheet on varying cell ranges?

I know there's many StackOverlow Q&A's on copying & pasting from a cell value in VBA. However, I can't seem to make it work for my own project. I want to copy the entire row(s) if it matches the Distinct Store# (non incremental) in Column H into a new sheet (in this code below, "Sheet1") which already has a template layout where I copy/paste the values. The template looks the same on every sheet before any data is filled in, except the first 2 tabs which have the data ("Appointments" and "Invoices").
I came up with the VBA below, but here's the catch- the cell# that it pastes the row(s) (in the code below, "A10") changes based on the Store #. This is because I am copying rows from the 1st sheet ("Appointments") in the workbook from the distinct Store#, then deleting the empty rows above the area where the 2nd sheet ("Invoices") data goes. Some stores may return 10 rows or none at all. The Case, which is the Store #, is currently manually put in one by one. Should it be an array instead?
Anyway...I was hoping to automate the copying/pasting and loop for each store to their sheet. Maybe I'm going about this wrong, but would anyone be kind enough to suggest how to solve my error code "Method or data member not found." as well as provide any suggestions on making my code better for a loop for filtered cell copying to different spots for each sheet.
Simple explanation of my step by step process:
1.Filter Store # from "Appointments" sheet.
2. Copy all rows for that store and paste into a new sheet with template named "Sheet1" in B3.
3. Filter Store # from "Invoices" sheet.
4. Copy all rows for that store and paste into the previously made sheet named "Sheet" under the above rows. (Some stores do not have invoices, so this section is blank/NULL). Paste destination cell for "Invoices" will be different for each store# depending on how many rows they get from the "Appointments" sheet (could be A10 or A25).
5. LOOP- Next store #, next sheet (sheet2).
Sub CopyToNewSheetInv()
Dim i As Range
Dim book As Workbooks
Dim sheet1 As Worksheets
Dim sheet2 As Worksheets
Set book = Workbooks("SampleWorkbookName")
Set sheet1 = Worksheets("AllInvoices")
Set sheet2 = Worksheets("Sheet1")
For Each i In sheet1.Range("H:H")
Select Case i.Value
Case 1243
sheet2.Range("A10").End(xlUp).Offset(1, 0).EntireRow.Value = i.EntireRow.Value
Case Else
End Select
Next i
End Sub
Try this:
Sub CopyToNewSheetInv()
Dim i As Range
Dim book As Workbook
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Set book = Workbooks("SampleWorkbookName.xlsx")
Set sheet1 = book.Worksheets("AllInvoices")
Set sheet2 = book.Worksheets("Sheet1")
'iterate only thorugh those cells in H that have data, not all 1.04 million
For Each i In sheet1.Range("H1", sheet1.Range("H" & sheet1.Rows.Count).End(xlUp))
Select Case i.Value
Case 1243,"1243"
sheet2.Rows(sheet2.Range("A10000").End(xlUp).Offset(1, 0).Row).Value = sheet1.Rows(i.Row).Value
Case Else
End Select
Next i
End Sub

Vba: vlookup for entire column

I have column B with cost centre codes and column D with department. i need to do a vlookup to fill in the department name of the relevant cost centre code.
The current code is like this:
Dim MyStringVar1= Application.Vlookup(Range("B7"),_
Worksheets("VLOOKUP Table").Range("A2:B1000"),2,True)
However, i dont just want to do vlookup for D7 only but rather the entire column. My range is not fixed(there may be 100 or 200rows in Column B,depending on the number of projects.)
How do I apply the formula for the entire column? Instead of D7 only
let's say you want to add formula =VLOOKUP(B2,'VLOOKUP Table'!A$2:B$1000,2,TRUE)
to range D3:D10, where 'B2' will increment after every row, then the code would be :
Range("D3:D10").Formula= "=VLOOKUP(B2,'VLOOKUP Table'!A$2:B$1000,2,TRUE)"
Dim This As Worksheet
Set This = ThisWorkbook.Sheets(1)
This.Activate
This.Range("D7", Range("A2").End(xlDown).Offset(0, 3)).Formula = "=VLOOKUP(B2,[INSERT SHEET]!$A:$D,2,FALSE)"
If the data is in sheet2, you just insert sheet2 in the [INSERT SHEET]. It doesn't matter if the name is sheet2 or named something else, just call it sheet2
You could use relative references in an R1C1 formula, then just paste it to your destination range, you'd need to find the destination range first, perhaps using something like .end(xldown).row
See this for reference on the general idea:
http://macromatician.blogspot.co.uk/2013/02/how-to-add-formula-to-worksheet-range.html

Best way to return data from multiple columns into one row?

I have a sheet with just order numbers and another with order numbers and all of the data associated with those order numbers. I want to match the order numbers and transfer all of the available data into the other sheet. I've been trying to use loops and VLOOKUP but I'm having problems (plus I have 116 columns I want to transfer data from so my vlookup expression doesn't look very nice). Any advice would be appreciated!
this is what I have so far and I'm getting an object error.
I don't think it's the right way to go about it in general though.
Dim LookUpRange As Range
Dim row As Range
Set LookUpRange = Worksheets("batches").Range("B4:B1384")
Set row = Worksheets("batches").Range("C:DL")
For Each row In LookUpRange
row.Select
Selection.FormulaArray ="=VLOOKUP(RC[-1],OrderLvl!RC[-1]:R[1380]C[113],{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,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,207,108,109,110,111,112,113,114,115},FALSE)"
Next row
End Sub
Please consider this VBA script to resolve your inquiry:
Sub LookupOuput()
Dim OrderNumberColumn As Range
Set OrderNumberColumn = Worksheets("batches").Range("B2:B1384")
Dim LookUpRange As Range
Set LookUpRange = Worksheets("OrderLvl").Range("C:DL")
Dim cell As Range
Dim FindResult As Range
For Each cell In OrderNumberColumn
If Not cell.Value2 = Empty Then
Set FindResult = LookUpRange.Find(what:=cell.Value2)
If Not FindResult Is Nothing Then
cell.Range("A1:DJ1").Value2 = LookUpRange.Rows(FindResult.row).Value2
End If
End If
Next cell
End Sub
Basically searches for each Order Number in the first sheet on the second sheet. This outputs (if search term exists) the cell that that string is found which we later refer to its row number to output the whole row to the first sheet. Cheers,
A regular VLOOKUP may be able to give you what you need, if you use a small trick...
Insert a row above the data table, and put sequential numbers in
each cell of that row. (ie, A1 = 1, B1 = 2, C1 = 3, etc...)
Do the same thing on your blank table.
Assuming that your first order number is in cell A2, put the following formula into B2: =VLOOKUP($A2,[other sheet name]!$A$1:$DZ$5000,B$1,0)
Drag this formula across all 116 columns, then down all however many rows you've got.
You'll need to adjust the ranges, obviously, but make sure that your lookup array starts in column A. (or alternatively, that your numbers start in the same column as the first column in your array.) Adding the numbers along the top allows you to change what column of the array you're referencing, just by dragging the cell formula.