Multiply numbers in Excel or LibreOffice cell contents by a constant when they are mixed with text? - excel

I have a long series of cells written like this (example text):
Example Number (3502, 456)
How would I multiply the numbers by 4 without having to delete the text?
I also have cells in the format [sic below]:
Example Number (3502,456) (4560,250) (2345,223)
et cetera, there are on average ten parentheses per text string.
Occasionally, the text might also be only one word long, e.g.
Example (3205, 456)
or
Example (3205,456) (4560,250) (2345,223)
et cetera.
(all above is [sic]).
As a sort of newbie to Excel (well, really Libre Office Calc but it's essentially the same), how would I do this? I don't want to go through and manually multiply all the numbers myself. The number I want to multiply by is 4. I've tried just running a find-and-replace to replace all ,'s and )'s with *4's, but the program I need these numbers for can't evaluate expressions, it needs single numbers.
There are some 110+ items on each list I need to change, and just one math error on any of the three lists (!) and the program won't run correctly (I'm resizing an image, and the points I plotted on the image didn't scale up with it). I don't want to risk it.

It should be possible to do this with a macro but unless I'm mistaken LibreOffice macro code is quite different from Excel VBA.
However if you can afford to use several columns of your spreadsheet to figure the values out, you can do so using formulae. If cell A1 contains
Example Number (3502,456) (4560,250) (2345,223)
and B1 contains
=MID(A1,FIND("(",A1)+1,9999)
then this formula will return the 3502 as a number:
=NUMBERVALUE(LEFT(B1,FIND(",",B1)-1))
(9999 is chosen to be much larger than the likely length of any line, so the MID function will always return the whole of the rest of the text after the search character).
You should be able to combine MID and FIND functions in further cells to isolate the other numbers, assuming these are always found in the format (xxx,yyy) as per your example. Then you can use a final formula to rebuild the string from the multiplied numbers:
="Example Number (" & 4*C1 & "," & 4*E1 & ")"
and so on.
If your data has a variable number of numbers to find, some of your FIND functions may return a #VALUE error. You may need to use an IF function to exclude these, for example:
=IF(ISERROR(G1),"",G1)
would return the value of G1 if it contains data, but blank if it contains an error.

Here is a Python LibreOffice macro that does what you want. It assumes all of the values are in column A, and it writes the results to column B.
import re
def do_calculations():
document = XSCRIPTCONTEXT.getDocument()
sheet = document.getSheets().getByIndex(0)
cellrange = sheet.getCellRangeByName("A1:A10000")
row_tuples = cellrange.getDataArray()
row = 1
for row_tuple in row_tuples:
if row_tuple:
row = output_values(row, row_tuple[0], sheet)
def output_values(row, pairs_string, sheet):
"""Multiply pairs of values by 4 and output each pair to B column.
:param row: the row number in the B column
:param pairs_string: a string like "Example Number (123, 456) (789, 1011)"
:param sheet: the current spreadsheet
Returns the next row number in the B column.
"""
pairs = re.findall(r'\([^)]+\)', pairs_string)
for pair in pairs:
match_obj = re.match(r'\((\d+),\s*(\d+)\)', pair)
x, y = match_obj.groups()
result = "(%d,%d)" % (int(x) * 4, int(y) * 4)
cell = sheet.getCellRangeByName("B" + str(row))
cell.setString(result)
row += 1
return row
# Functions that can be called from Tools -> Macros -> Run Macro.
g_exportedScripts = do_calculations,
Save the code to a text file, for example calc_multiply_numbers.py. Put it in Scripts/python in your LibreOffice user directory. On my Windows system it is C:\Users\JimStandard\AppData\Roaming\LibreOffice\4\user\Scripts\python. If the python directory doesn't exist yet, create it.
To run it, open the spreadsheet and go to Tools -> Macros -> Run Macro. Under My Macros, click calc_multiply_numbers and then press the Run button.
EDIT:
I don't think you need to worry about the JRE error. On my system I can uncheck "Use a Java runtime environment" in Tools -> Options -> LibreOffice -> Advanced, and it still works. I just click "No" when it asks if I want to enable the use of a JRE now, and then it runs my python macro.
The reason it is not showing up under My Macros is because python is not able to interpret the file correctly. To find the error, test it with python using the following steps (assuming Windows):
Open a command prompt, for example by pressing Win, typing cmd, and clicking "Command Prompt" from the start menu.
Type cd "path-to-libreoffice/program". On my 64-bit system this is cd "C:\Program Files (x86)\LibreOffice 5\program" I use the normal Windows File Explorer to find the exact path.
Type "python.exe python-script". On my system it is python.exe "C:\Users\JimStandard\AppData\Roaming\LibreOffice\4\user\Scripts\python\calc_multiply_numbers.py"
The python interpreter will give an error message about the problem. If you are not able to figure out the message, write it in the comments below and I will help you.

Related

Data extraction from excel with operators is unable to store values

I have a Excel file with two columns. One has a name other has the corresponding mass to it. I have used the corresponding lines to read it and find the position of the name. But when I am trying to find the mass to the corresponding name as shown below it is not able to store it in the memory. In the Excel file, I have the mass values as 1.989*10^30. This seems to affect the code as the same code works fine when the cells in the excel has just numeric values.
majbod = 'Sun';
minbod = 'Earth';
majbodin = readtable("Major_and_Minor_Bodies.xlsx","Sheet",1);
minbodin = readtable("Major_and_Minor_Bodies.xlsx","Sheet",2);
MAJORBODY = table2array(majbodin(:,"Major_Body"));
MINORBODY = table2array(minbodin(:,"Minor_Body"));
mmaj = table2array(majbodin(:,"Mass"));
mmin = table2array(minbodin(:,"Mass"));
selected_majbody = find(strcmp(MAJORBODY,majbod));
selected_minbody = find(strcmp(MINORBODY,minbod));
M = mmaj(selected_majbody);
m = mmin(selected_minbody);
disp([M ;m])
Is there a better way to write the code compared to the way which I wrote?
Thanks.
Excel does it's best to figure out what kind of data is in each cell. Since your data has something besides just numbers, Excel treats it like a string. You have a couple of options for getting around that:
If you put an equals sign in front of it, it will treat it like an equation, and calculate the value of 1.989*10^3 for you. this will be a number.
Since scientific notation is so common, programmers have created a shortcut for representing it. They often use the character 'E' where you use "*10^". This means that if you type "1.989E30", excel will recognize that as a number.
If keeping the current string format is very important, you could probably modify the string during extraction - replace '*10^' with E, and then whatever language you are using will have a string to number parser you can use.
If the real problem is that the real numbers are just too long in Excel, you can always format the cell that they are in. (right click the cell, select format cells, then select scientific.)
Good luck

Making a vector out of excel columns using python

everyone...
I just started on python a couple of days ago because I require to handle some excel data in order to automatically update the data of certain cells from one file into another.
However, I'm kind of stuck since I have barely programmed before, and it's my first time using python as well, but my job required me to find a solution and I'm trying to make it work even though it's not my field of expertise.
I used the "xlrd library", imported my file and managed to print the columns I'm needing... However, I can't find a way to put those columns into a matrix in order to handle the data like this:
Matrix =[DataColumnA DataColumnG DataColumnH] in the size [nrows x 3]
As for now, I have 3 different outputs for the 3 different columns I need, but I'm trying to join them together into one big matrix.
So far my code looks like this:
import xlrd
workbook = xlrd.open_workbook("190219_serviciosWRAmanualV5.xls");
worksheet = workbook.sheet_by_name("ServiciosDWDM");
workbook2 = xlrd.open_workbook("Potencia2.xlsx");
worksheet2 = workbook2.sheet_by_name("Hoja1");
filas = worksheet.nrows
filas2 = worksheet2.nrows
columnas = worksheet.ncols
for row in range (2, filas):
Equipo_A = worksheet.cell(row,12).value
Client_A = worksheet.cell(row,13).value
Line_A = worksheet.cell(row, 14).value
print (Equipo_A, Line_A, Client_A)
So I have only gotten, as mentioned above, the data in the columns which is what I'm printing which you can see.
What I'm trying to do, or the main thing I need to do is to read the cell of the first row in Column A and look for it in the other excel file... if the names match, I would have to validate that for the same row (in file 1) the data in both the ColumnG and ColumnH is the same as the data in the second file.
If they match I would have to update Column J in the first file with the data from the second file.
My other approach is to retrieve the value of the cell in ColumnA and look for it in the column A of the second file, then I would make an if conditional to see if ColumnsG and H are equal to Column C of 2nd file and so on...
The thing here is, I have no idea how to pin point the position of the cell and extract the data to make the conditional for this second approach.
I'm not sure if by making that matrix my approach is okay or if the second way is better, so any suggestion would be absolutely appreciated.
Thank you in advance!

How can I use four time equal (ex. ====) in excel formula

I'm unable to use below formula in excel
400+rate÷400×principal====
Ex.
Do this in calculator:
400+9.05÷400×10000
Now press four times the equal button. Answer is 10936.17. But I'm unable to do this in Excel. I hope someone may help me.
You don't need to write ====, just one = is enough. Also, use * and not x, use / and not ÷.
If you want the result to be 10226.25, you need some math predecessors using brackets ().
Enter this equation in a cell:
=(400+9.05)/400*10000
This gives the expected outcome:
10226.25
Whenever you press = in the calculator you are multiplying the result by the operation before it
400+9.05=409.05 you will get the result without =in the calculator if you only press ÷
409.05 ÷ 400 = 1.022625 this is the number that each time you press = will multiply the result in the calculator
you write X 10000 and first = 10266.25 first result
second = is 1.022625 X 10266.25 second result 10457.62
third = is 1.022625 X 10457.62 third result 10694.22
fourth = is 1.022625 X 10694.22 fourth result 10936.18 your outcome
In Excel you have to write:
=(((400+9.05)/400)^4)*10000 to have the same outcome
It's true that Excel can be used as a Calculator up to certain extent,, but it's not created to act like a Calc,, always remember ever calculation begins with = sign followed either by Function or data.
So finally you should write your Formula like this,
=(400+9.05) /(400×10000)
You might find a parameterised version useful:
The inputs are shown in blue, the output in F2 where the formula is:
=C2*((A2+B2)/A2)^D2
D2 is effectively the number of equals signs depressed on your calculator.

Creation of vector of unknown size in Excel

I am attempting to translate my existing Matlab code into Numbers (basically Excel). In Matlab, I have the following code:
clear all; clc;
n = 30
x = 1:(n-1)
T = 295;
D = T./(n-x)
E = T/n
for i=1:(n-2)
C(i) = D(i+1) - D(i)
end
hold on
plot(x(1:end-1), C, 'rx')
plot(x, D, 'bx')
I believe everything has been solved by your formulas, there are parts of them that I don't understand otherwise I would try to figure the rest out myself. Attached is the result (Also you might like to know that the formulas you gave work and are recognized in Numbers). Im trying to figure out why (x) begins at 2 as I feel as though it should start at 1?
Also it is clear that the realistic results for the formulas only exist under certain conditions i.e. column E > 0. That being the case, what would be the easiest way to chart data with a filter so that only certain data is charted?
(Using Excel...)
Suppose you put your input values T & n in A1 & B1 respectively.
You could generate x, D & C In columns C,D & E with:
C1: =IF(ROW()<$A$1,ROW(),"")
D1: =IF(LEN(C1)>0,$A$2/($A$1-C1),"")
E1: =IF(LEN(D2)>0,D2-D1,"")
You could then pull all 3 columns down as far as you need to generate the full length of your vectors. If you then want to chart these, simply use these columns as inputs.

Copying all #mentions and #hashtags from column A to Columns B and C in Excel

I have a really large database of tweets. Most of the tweets have multiple #hashtags and #mentions. I want all the #hashtags separated with a space in one column and all the #mentions in another column. I already know how to extract the first occurrence of a #hashtag and a #mention. But I don't know to get them all? Some of the tweets have as much as 8 #hashtags. Manually going through the tweets and copy/pasting the #hashtags and #mentions seem an impossible task for over 5,000 tweets.
Here is an example of what I want. I have Column A and I want a macro that would populate columns B and C. (I'm on Windows &, Excel 2010)
Column A
-----------
Dear #DavidStern, #spurs put a quality team on the floor and should have beat the #heat. Leave #Pop alone. #Spurs a classy organization.
Live broadcast from #Nacho_xtreme: "Papelucho Radio"http://mixlr.com nachoxtreme-radio … #mixlr #pop #dance
"Since You Left" by #EmilNow now playing on KGUP 106.5FM. Listen now on http://www.kgup1065.com  #Pop #Rock
Family Night #battleofthegenerations Dad has the #Monkeys Mom has #DonnieOsman #michaelbuble for me #Dubstep for the boys#Pop for sissy
#McKinzeepowell #m0ore21 I love that the PNW and the Midwest are on the same page!! #Pop
I want Column B to look like This:
Column B
--------
#DavidStern #Pop #Spurs
#mixlr #pop #dance
#Pop #Rock
#battleofthegenerations #Monkeys #DonnieOsman #Dubstep #Pop
#pop
And Column C to look like this:
Column C:
----------
#spurs #heat
#Nacho_xtreme
#EmilNow
#michaelbuble
#McKinzeepowell #m0ore21
Consider using regular expressions.
You can use regular expressions within VBA by adding a reference to Microsoft VBScript Regular Expressions 5.5 from Tools -> References.
Here is a good starting point, with a number of useful links.
Updated
After adding a reference to the Regular Expressions library, put the following function in a VBA module:
Public Function JoinMatches(text As String, start As String)
Dim re As New RegExp, matches As MatchCollection, match As match
re.pattern = start & "\w*"
re.Global = True
Set matches = re.Execute(text)
For Each match In matches
JoinMatches = JoinMatches & " " & match.Value
Next
JoinMatches = Mid(JoinMatches, 2)
End Function
Then, in cell B1 put the following formula (for the hashtags):
=JoinMatches(A1,"#")
In column C1 put the following formula:
=JoinMatches(A1,"#")
Now you can copy just the formulas all the way down.
you could convert text to columns using the other character #, then against for #s and then concatenate the rest of the text back together for column A, if you are not familiar with regular expressions see (#Zev-Spitz)

Resources