Excel Macro to Convert Cell Data to Multiple Columns - vba

I have a big bunch of cells in Excel that look like the following:
FName LName, Loc JB
Abbreviations are bad, so: First Name, Last Name, Location, Job.
I need to move that so it looks like this:
FName LName || LOC || JB
Caveats:
Must remove the , after the name.
Must capitalize the location (it's 2 or 3 letters, inconsistently capitalized. I want to make them all caps).
JB is anywhere from 1 to 4 characters on the end. I just need to take that last bit and dump it in.
They're all separated by at least a space (the first has a comma and a space).
I'd like a macro to do this, because I have to do it with relative frequency, and doing 200 rows of this by hand is a pain. Any help?

Sounds like all you need is a formula in the next column. If your values are in column A starting with cell A1, try:
=LEFT(A1,FIND(",",A1)-1)&" || "&UPPER(MID(A1,FIND(",",A1)+2,FIND(" ",A1,FIND(",",A1)+2)-FIND(",",A1)-2))&" || "&RIGHT(A1,LEN(A1)-FIND(" ",A1,FIND(",",A1)+2))
This formula takes everything to the left of the comma and adds " || ". Then it finds the next space starting its search two characters after the comma. Using that index it then can extract the location and make it upper case. Then again we add " || ". Then knowing the index of that space we can grab everything to the right to grab the job. This same logic can be applied in VBA but this is probably a quicker solution and easier to pass between computers.

You don't necessarily need a macro. You can do it with a series of right()'s left()'s mid()'s and find()'s. Also need to use Upper() for the loc.
For instance, if your data is in column A, to get a column with first and last name in column B, in B1 you could use:
=LEFT(A1,FIND(",",A1)-1)
That'll return everything up to but not including the comma. For Loc, assuming there's a comma between Loc and JB in C1 you'd use:
=UPPER(MID(A1,FIND(",",A1)+2,FIND(",",A1,FIND(" ",A1)+1)-FIND(" ",A1)-3))
That'll return the uppercase version of the middle of the string, starting 2 chars after the first comma (so you don't get the space), and ending 2 less than the difference between the first and second commas. If there's no comma, you could do a similar set of searches to find where that last space is.
The last IN d1 is:
=RIGHT(A1,LEN(A1)-FIND(" ",A1,FIND(",",A1)+2))
edited after the clarification of commas and spaces.

Related

Query to retrieve only columns which have last name starting with 'K'

]
The name column has both first and last name in one column.
Look at the 'rep' column. How do I filter only those rep names where the last name is starting with 'K'?
The way that table is defined won't allow you to do that query reliably--particularly if you have international names in the table. Not all names come with the given name first and the family name second. In Asia, for example, it is quite common to write names in the opposite order.
That said, assuming you have all western names, it is possible to get the information you need--but your indexes won't be able to help you. It will be slower than if your data had been broken out properly.
SELECT rep,
RTRIM(LEFT(LTRIM(RIGHT(rep, LEN(rep) - CHARINDEX(' ', rep))), CHARINDEX(' ', LTRIM(RIGHT(rep, LEN(rep) - CHARINDEX(' ', rep)))) - 1)) as family_name
WHERE family_name LIKE 'K%'
So what's going on in that query is some string manipulation. The dialect up there is SQL Server, so you'll have to refer to your vendor's string manipulation function. This picks the second word, and assumes the family name is the second word.
LEFT(str, num) takes the number of characters calculated from the left of the string
RIGHT(str, num) takes the number of characters calculated from the right of the string
CHARINDEX(char, str) finds the first index of a character
So you are getting the RIGHT side of the string where the count is the length of the string minus the first instance of a space character. Then we are getting the LEFT side of the remaining string the same way. Essentially if you had a name with 3 parts, this will always pick the second one.
You could probably do this with SUBSTRING(str, start, end), but you do need to calculate where that is precisely, using only the string itself.
Hopefully you can see where there are all kinds of edge cases where this could fail:
There are a couple records with a middle name
The family name is recorded first
Some records have a title (Mr., Lord, Dr.)
It would be better if you could separate the name into different columns and then the query would be trivial--and you have the benefit of your indexes as well.
Your other option is to create a stored procedure, and do the calculations a bit more precisely and in a way that is easier to read.
Assuming that the name is <firstname> <lastname> you can use:
where rep like '% K%'

Blank Space in every row of table SQL

Hello i have a table with rows
and i was doing a simple
select from table where column ='string'
and it gives me back no result, but when i use:
select from table where column ='%string%'
it gives me the row that exist in my table,
then i did a select * from table and noticed that there is a blank space before my rows:
Image of my SQL result
If you look closely theres a space at the beginning of the second row, and only in the first row theres no blank space.
so i thought it was a simple white space at the beggining but when i tried using this:
SELECT LTRIM(RTRIM(MATERIAL)) FROM table
nothing happened.
then i tried to copy the result of my
select * from table
to Excel and noticed this:
Excel paste from SQL
my 2nd row got splitted in 2 rows right at the start of the column 'material', so the thing i thught it was a blank space its something like a jump line.
i have never had this problem before or seen this before.
Larnu has commented how to remove all the linebreaks from the data. Here are some other things that could also work, and slightly differently depending on the effect you want:
--trim everything that is not a number or letter off the left hand side only
UPDATE table SET material = SUBSTRING(material, PATINDEX(material, '[0-9a-z]', 99999)
--convert all linebreaks to spaces and trim off the left and right spaces
UPDATE table SET material = RTRIM(LTRIM(REPLACE(material, CHAR(10), ' ')))
Larnu's SQL isn't wrong, it'll just remove every line break anywhere, which may cause more formatting disruption than is wanted. I'd be tempted to replace all the linebreaks with spaces, as two words that are separated by a line break would remain separated by a space rather than become one word if the space was removed
some
word
-> some word (if you replace linebreak with space)
-> someword (if you replace linebreak with nothing)
If all you want is to remove linebreaks from the left side of the field, the patindex method will search the field for the first occurrence of a numbe rof a letter, and return the index, then substring will cut everything from that index for a length of 99999 (use a bigger number if your field is longer). This has the effect of removing only linebreaks at the start of the field
As to how it happened, whoever inserted the data, or the data import program, made some mistakes when it was cutting up the data. Perhaps it was a Windows style text file, whose line endings are CR LF (ascci 13 followed by 10), and the program that did the import decided to cut the file up based on the 13 only, leaving behind the 10 to become "part of" the material field:
this,is,my,data1<13><10>this,is,my,data2<13><10>
//now lets cut it up into 2 records, based on using <13> only to denote the end of line:
record 1= this,is,my,data1
record 2= <10>this,is,my,data2
The program just sees a stream of bytes, it is we humans that interpret "lines". If the program treats 13 as the separator, then all the 10s get left behind as part of the data that gets inserted. The very first record in the file won't have 13/10 (crlf) before it because it's the first line, so one of your rows (the one with ascii (49)) won't suffer this problem
You could "cure" the bad data with a trigger upon insert:
CREATE TRIGGER prevent_bad_data
ON yourtable
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO yourtable(somecolumn,othercolumn,material)
SELECT foo,
bar,
LTRIM(REPLACE(material, CHAR(10), ' '))
FROM Inserted
END
Or you could program the db to reject bad rows and fix the tool that is inserting the bad data:
ALTER TABLE yourtable
ADD CONSTRAINT prevent_bad_material
CHECK material LIKE '[0-9a-z]%'; --check it starts with a number or letter
Edit: though having seen your updated question with screenshots, the material column really should be a number, not a varchar type, then this wouldn't happen

Hi, I need a SQL query each cell in a column must contain a least one alpha character (A-Z, a-z)

I need help with a a SQL query where each cell in a column must contain a least one alpha character (A-Z, a-z).
I have tried different combinations of ISNUMERIC, LIKE & ISALPHABET & also searched google but cant work it out. IS Alphanumeric also does not work for this situation.
The input in the column is :
3
3-5
3 RYDE ST
RYDE ST
I want the output to be Row 1 & 2 as below, because these do not include an alpha character. I will then manually alter the cells to ensure they meet the condition to have at least one alpha character:
3
3-5
SELECT column_name
FROM table_name
WHERE column_name
LIKE '%[A-Za-z]%'
The % matches anything. So you are looking for anything followed by a letter followed by anything.
http://www.w3schools.com/sql/sql_wildcards.asp

How to remove unwanted spaces between the text in excel2007

I want to remove or delete the extra spaces in character value. For example the col contains the name data like:
"sachin sa meer pa war"
Actually i want this in one line with only 2 spaces like:
"sachin sameer pawar"
This will make me easy to text to col function.
So how can i remove those two unwanted spaces which is in between the middle name and in last name?
Since you specifically mention "those two unwanted spaces":
=SUBSTITUTE(SUBSTITUTE(A4," ","",2)," ","",3)

how do I retrieve data from a sql table with huge number of inputs for a single column

I have a Company table in SQL Server and I would like to retrieve list of data related to particular companies and list of companies is very huge of around 200 company names and I am trying to use IN clause of T-SQL which is complicating the retrieval as few the companies have special characters in their name like O'Brien and so its throwing up an error as it is obvious.
SELECT *
FROM COMPANY
WHERE COMPANYNAME IN
('Archer Daniels Midland'
'Shell Trading (US) Company - Financial'
'Redwood Fund, LLC'
'Bunge Global Agribusiness - Matt Thibodeaux'
'PTG, LLC'
'Morgan Stanley Capital Group'
'Vitol Inc.'..
.....
....
.....)
Above is the script that is not working for obvious reasons, is there any way I can input those company names from an excel file and retrieve the data?
The easiest way would be to make a table and join it:
CREATE TABLE dbo.IncludedCompanies (CompanyName varchar(1000)
INSERT INTO dbo.IncludedCompanies
VALUES
('Archer Daniels Midland'),
('PTG, LLC')
...
SELECT *
FROM Company C
JOIN IncludedCompanies IC
ON C.CompanyName = IC.CompanyName
I do not think that mysql knows how to handle excel format, but you can fix your query.
Check how complicated names are stored in database (check if they have escape characters in them or anything else".
Replace all ' with \' in your query and it will take care of the ' characters
mysql> select now() as 'O\'Brian'; returns
O'Brian
2014-03-17 15:06:39
So i'm guessing you have a excel sheet with a column containing these names, and you want to use this in your where clause. In addition, some of the values have special characters in them, which needs to be escaped.
First thing you do is to escape the '-characters. You do this in excel, with a search replace for all occurences of ' with '' (the escaped version in sqlserver (\' in MySQL.)) Then, create a new column on each side side of your companies column, and in the first row input a ' on the left hand side, and ', on the right. Then use the copy cell functionality (the little square in the bottom right of the cell when you select it) to copy the cells to the left and right to all the rows, as far as the company list goes (just grab the square and pull it downwards..)
Then, take your list, now containing three columns and x rows and paste it into your favorite text editor. It should look something like this:
' Company#1 ',
' Company with special '' char ',
[...]
' Last company ',
Now, you will have some whitespace to get rid of. Use search replace and replace two space characters with nothing, and repeat (or take the space from the first ' to the start of the text and replace this with nothing.
Now, you should have a list of:
'Company#1',
'Company with special '' char',
[...]
'Last company',
Remove the last comma, and you'll have a valid list of parameters to your in-clause (or a (temporary) table if you want to keep your query a bit cleaner.)