excel 2007: append certain characters to value in a column to make it proper lenght - excel-2007

I have following values in a column :
123
456
789
65
1
I want to append correct number of zeros in all the values in that column such that the total length of character is 5.
00123
00456
00789
00065
00001
How do I do that?

If there is one number per cell, you can do this easily by changing the format to "Custom."
Right-click on the cells you would like to format.
From the context menu, choose "Format cells"
Choose the Custom category.
Over the word "General," in the Type textbox, enter 00000. (This tells Excel to print with
leading 0s).
Click OK.
If the number is bigger than five digits, it will print all of the digits.
===EDIT===
You explained that these were all in one cell. #paulmorriss has an excellent Excel-function-only solution, but let me proffer a VBA solution as an alternative:
Sub Macro1()
Dim txt As String
Dim asWords() As String
Dim zeros As String
txt = vbNullString
asWords = Split(Range("A1").Value) 'asWords(0)="123" etc.
For i = 0 To UBound(asWords) ' emulate StrDup (missing in VBA)
zeros = vbNullString
For j = Len(asWords(i)) + 1 To 5: zeros = zeros + "0": Next j
txt = txt + zeros + asWords(i) + " "
Next i
Range("B1").Value = txt 'Places answer in B1
End Sub

If the value you specify is in cell A1 then put the following formulae in B1 to K1. The value in K1 is what you need. You could specify one massive formula, but it's easier for people maintaining the spreadsheet to see what's going on if it's split up like this.
in B1 =TEXT(VALUE(LEFT(A1,SEARCH(" ",A1))),"000000")
in C1 =RIGHT(A1,LEN(A1)-SEARCH(" ",A1))
etc. =TEXT(VALUE(LEFT(C1,SEARCH(" ",C1))),"000000")
=RIGHT(C1,LEN(C1)-SEARCH(" ",C1))
=TEXT(VALUE(LEFT(E1,SEARCH(" ",E1))),"000000")
=RIGHT(E1,LEN(E1)-SEARCH(" ",E1))
=TEXT(VALUE(LEFT(G1,SEARCH(" ",G1))),"000000")
=RIGHT(G1,LEN(G1)-SEARCH(" ",G1))
=TEXT(I1,"000000")
=B1&" "&D1&" "&F1&" "&H1&" "&J1

Related

How to put character if there is one digit in cell in VBA Macro?

I would like to ask, how to put character, in this case 0 to cell, if the cell already contains digit in it.
To clarify what do I mean, if on the cell is number 5, I would like to put before the number 5, number 0 to have the result 05.
As far as I know, cell format should be TEXT to avoid automatic Excel correction. But, this question is specific due to several different characters in the cells. In some point I got in the same column different characters in the cells (1, 2, 3, AV, AR, IX etc.).
For example: I would like to select column K, find the numeric characters with one digit (1, 2, 3, -9) and paste there 0 before it to have two space digit like 01, 02, 03, …
Of course, with macro. I know how to put Text format to it, but do not know how to manage the whole macro function to select column K, format whole column as text, find one digit number in the column and paste 0 before it.
Does anybody know how to do that?
Many thanks in advance.
There are 2 solutions:
Format the numbers
Convert numbers to text and format them
1. Format the numbers
The advantage of this solution is that the numbers will still be numbers (not text) but formatted with leading zeros. Therefore you still can calculate with these numbers as before.
Public Sub ChangeNumberFormat()
ThisWorkbook.Worksheets("YourDesiredSheetName").Columns("K").NumberFormat = "00"
'this will keep them numbers but only change the format of them
End Sub
Note that you don't need to do this necessarily with VBA you can just set a user defined cell format 00 for column K (open format cells with Ctrl + 1).
2. Convert numbers to text and format them
If you really need to convert them to text this would be a possible solution. But I really don't recommend that because you cannot calculate with these "numbers" anymore because they are converted to text.
The trick would be to format the number with numberformat first and then convert it to text (see comments in the code).
Option Explicit 'force variable declaring
Public Sub FixLeadingZerosInText()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("YourDesiredSheetName") '<-- change your sheet name here
Dim lRow As Long
lRow = ws.Cells(ws.Rows.Count, "K").End(xlUp).Row 'find last used row in column K
Dim iCell As Range
For Each iCell In ws.Range("K1:K" & lRow) 'loop from row 1 to last used in column K
If iCell.Value < 10 And iCell.Value > -10 Then 'check if it is a one digit number
Dim tmpText As String
tmpText = Format(iCell.Value, "00") 'format the one digit number
iCell.NumberFormat = "#" 'convert number to text
iCell.Value = tmpText 're-write formatted number
End If
iCell.NumberFormat = "#" 'make all other numbers in column K formatted as text too
Next iCell
End Sub

Copying a specfic line within a cell into another cell

I have a spreadsheet that has multiple lines within a cell, all with line breaks.
e.g.
Name: a
Age: 1
University: 1
Degree: 3
Year: 3
I am looking to extract (in this example) the University infomation that is contained within the cell and copy it into another cell in another column.
There are about 1000 records in my document so to copy and paste by hand will be time consuming.
Any help will be appreciated
Cheers
Joe
You could do this with an Excel formula.
Assuming your data is in column A, and you want the extraction in column B, and assuming you put a title in row 1, you could do as in the following image:
(Note that I have a semi-colon in the formula as list separator, use comma instead)
The formula in B2 is:
=MID($A2, FIND(B$1, $A2) + LEN(B$1),
FIND(CHAR(10), $A2 & CHAR(10), FIND(B$1, $A2)) - FIND(B$1, $A2) - LEN(B$1))
The formula has some duplication; here are some of the parts explained:
FIND(B$1, $A2) returns the position of the title in the text
FIND(B$1, $A2) + LEN(B$1) returns the position of what follows that title in the text
FIND(CHAR(10), $A2 & CHAR(10), FIND(B$1, $A2)) returns the position of a newline character following the title, making sure that if none is present, a position beyond the string length is returned
As long as you put the column titles to whatever sub-string you are looking for, you can copy/drag the same formula to other columns and rows.
If there is a single break between each line, then in B1 enter:
=TRIM(MID(SUBSTITUTE($A1,CHAR(10),REPT(" ",999)),COLUMNS($A:C)*999-998,999))
This assumes that:
the university line is the third line
you want the entire line
I'm providing an answer even though you haven't provided what attempts you've made so far, which is how questions on this site usually work...but today I'm feeling generous :)
Use a combination of MID and FIND formulas, like the following:
=MID(A1,FIND("University",A1),FIND("Degree",A1)-FIND("University",A1)-2)
I put your example text in Cell A1 for my test, and it returned University: 1. This however will only work if University is always followed by Degree in the text strings.
The other method would be to replace the last part of your MID statement (the part asking for length to return) with the exact number of characters to return, which in this case would be 13, like the following:
=MID(A1,FIND("University",A1),13)
This assumes that the integer associated with University is always 1 character in length.
Either way, a combination of the above two formulas should get you what you need. VBA should not be necessary in this case.
Lines in a cell value are separated by the line feed character vbLf, so to extract the information out of the cell value you can use String-Functions Mid(...) and InStr(...):
Dim cellValue as String
Dim extracedValue as String
Dim keyWord as String
Dim posStart as Integer, posEnd as Integer
extractedValue = "" ' Not necessary, but I prefer initialized variables
cellValue = ActiveSheet.Cells(1,1).Value ' Put your cell here
keyWord = "University" ' Put your keyword here
posStart = InStr(1, cellValue, keyWord) ' Find keyword in the string
If (posStart > 0) Then
posEnd = InStr(posStart, cellValue, vbLf) ' Find next line feed after the keyword
If (posEnd > 0) Then
extractedValue = Mid(cellValue, posStart, posEnd - posStart) ' Extract the value
End If
End If
I haven't tested the code, but you should get the idea.

Excel VBA Text to Columns Backwards with maximum # of columns

Apples, Oranges, Strawberries, Pears, Almonds, Peanuts, Peaches
I would like to find "," from backwards (instrrev) and perform something similar to text to columns function in Excel, which would
#1 > Apples, Oranges
#2 > Apples | Oranges
perform action that takes #1 to #2.
However, I would like to have maximum columns of 5 (split into 5 pieces and the split-base character searched from backwards)
so that the top example would result in:
Apples, Oranges, Strawberries | Pears | Almonds | Peanuts | Peaches
Please keep in mind that it is possible for the text to have no commas, so I need to check if they exists first
Thanks for the help!
Try this, by putting your example text in a cell, selecting that cell and then running the below. You will need to test this, and possibly handle some scenarios yourself - but this code should get you going and works on your example.
Sub SplitIntoColumns()
Dim intMaxCols As Integer
Dim intCommaFoundPos As Integer
Dim intNumCommasFound As Integer
Dim strTextToCheck As String
Dim strFoundText As String
Dim intRowToWriteTo As Integer
Dim intColToWriteTo As Integer
'this should be max num of columns you want -1
intMaxCols = 4
'just putting the text into the activecell and running on that
strTextToCheck = ActiveCell
'row to write output to
intRowToWriteTo = 10
'column to write output to - it will go backwards from here
intColToWriteTo = 10
'find the comma
intCommaFoundPos = InStrRev(strTextToCheck, ",")
'if there is a comma
If intCommaFoundPos > 0 Then
'loop until you have looped the max columns number of times, or until there are no commas left in the string
Do Until (intNumCommasFound = intMaxCols) Or intCommaFoundPos = 0
'get comma position
intCommaFoundPos = InStrRev(strTextToCheck, ",")
'if there is still a comma
If intCommaFoundPos > 0 Then
'keep track of the number found
intNumCommasFound = intNumCommasFound + 1
'take everything to right of comma
strFoundText = Trim(Mid(strTextToCheck, intCommaFoundPos + 1, Len(strTextToCheck)))
'write to sheet, adjust next column number
ActiveSheet.Cells(intRowToWriteTo, intColToWriteTo) = strFoundText
intColToWriteTo = intColToWriteTo - 1
'change the text to check to not include the word just found
strTextToCheck = Left(strTextToCheck, intCommaFoundPos - 1)
End If
Loop
'if there is any text left, write to sheet
If Len(strTextToCheck) > 0 Then ActiveSheet.Cells(intRowToWriteTo, intColToWriteTo) = strTextToCheck
End If
End Sub
You can also implement it in formula:
=IF(LEN(A3)-LEN(SUBSTITUTE(A3,",",""))<5,SUBSTITUTE(A3,",","|"),REPLACE(A3,FIND("#",SUBSTITUTE(A3,",","#",LEN(A3)-LEN(SUBSTITUTE(A3,",",""))-4))+1,LEN(A3),SUBSTITUTE(MID(A3,FIND("#",SUBSTITUTE(A3,",","#",LEN(A3)-LEN(SUBSTITUTE(A3,",",""))-4))+1,LEN(A3)),",","|")))
with the string in A3
How it works:
Find out the number of "," in the string by subtracting length of comma-less string from full string.
if less than 5 commas then substitute all "," with "|"
if equal to or more than 5 commas then, find the character position of the 5th comma from right,and replace the string after that character position with the substituted string.

Excel pulling data from certain cells

I have a file that I only want to extract cells B9, B19, B29, etc etc etc in a pattern throughout the entire file. I would preferably like it to be extracted to a different excel file or someway so that I can do stuff with only those cells in another excel worksheet.
Potentially, I may have several excel files that I may need to do this sort of thing so if there were a way where I had the same format throughout a lot of files that I could always extract cells B9, B19, B29 that would be great. any help appreciated
I looking for syntax if possible
EDIT
Was thinking if I could somehow make an excel IF statement saying if Row has a 9 in it and the row is B then print it somewhere but I want it printed in a column
EDIT 2
I just want column B not A like I mentioned before.
B9, B19,B29,B39 through the whole file
Just in case you want to do it with code:
Sub Test()
'Assumes Sheet1 has your values and Sheet2 will be the data extracted from every row ending in 9
Dim iCounter As Long
Dim newSheetRow As Long
Dim aValue As String
Dim bValue As String
newSheetRow = 1
'Start and nine and increment by 10 till you reach end of sheet
For iCounter = 9 To Sheet1.Rows.Count - 1 Step 10 'NOTE: You may not want to do it by RowCount, but just showing you could
aValue = Sheet1.Range("A" & iCounter)
bValue = Sheet1.Range("B" & iCounter)
Sheet2.Range("A" & newSheetRow).Value = "We were on row: " & iCounter
Sheet2.Range("B" & newSheetRow).Value = aValue
Sheet2.Range("C" & newSheetRow).Value = bValue
newSheetRow = newSheetRow + 1
Next iCounter
MsgBox "Done"
End Sub
You could use the INDIRECT function. It takes a cell reference as a text string and returns the value in that cell. So instead of using
=data!a9
to get the value in sheet "data" in cell a9, you use
=indirect("data!a9")
You can also use r1c1 notation, like this:
=indirect("data!r9c1",false)
From there you can use the ROW and COLUMN functions to go in steps of 10:
=INDIRECT("data!r"&-1+10*ROW()&"c"&COLUMN(),FALSE)
If you put this formula in A1 of your output sheet and then copy and paste it down and across, it will give you the values in data!A9, data!A19, data!A29,... in cells A1, A2, A3... Depending on how you want your output arranged, you might have to modify the cell reference string.
Depending on how often you want to do this depends on how you need to do it, if it's a one of them some simple excel commands might help.
e.g.
In Cell C1 put the following:
=MOD(ROW(),10)
then replicate this down to the bottom of your data. the command will return the numbers 1 through to 0. You can then filter the data on column C where value is 9 then select the visible rows and copy the data to a new sheet.
ROW() ' this returns the ROW number of cell the command is in.
MOD(number, divisor) ' this basically divides one number by the other and returns the remainder. so row 9 / 10 = 0 remainder of 9, row 19 / 10 = 1 remainder of 9.
Hope this helps.

VBA: preceding zeros dropped when copied over

I am creating a copy of an Excel file using VBA. In the file, there is a column that includes numbers with preceding zeros. The copy of the file is created, but the data in this column is dropped. I need to keep the values with the preceding zeros. How can I resolve this problem with VBA?
The best way is to pre-format the column as Text by setting Range.NumberFormat to "#". This way, if a user edits the cell, the cell will stay as text and maintain it's leading zeros. Here is a VBA example:
ActiveSheet.Range("C:C").NumberFormat = "#"
Convert each cell in that column to a text field prior to exporting it. That should ensure that every character is retained (and not treated like a number, which is what it sounds like is happening).
An additional possibility is to append an apostrphe to each cell. This will treat all the values as text which is useful when different tabs treat common values as text vs number (ie copied in vs calculated).
This is done by using the Chr() function and assigning it the character code 39('):
For x = 1 to 100
If Sheets(origSheet).Cells(x, "A").Value <> "" Then
Sheets(origSheet).Cells(x, "A").Value = Chr(39) & Sheets(origSheet).Cells(x, "A").Value
End If
Given the accepted answer, it's probably not what you need, but setting a custom number format will also get the preceeding zeroes back into the displayed value.
To show a value with leading zeroes up to 8 digits, for example, set the format to 00000000, then 123 will be displayed as 00000123.
Both the method here and the format-as-text method will result in cell values that will still work in calculations, although horizontal alignment will be different by default. Note also that, for example, concatenating strings to the values will result in differences:
as text: displays 00000123, append "x" to get 00000123x
as number with custom format: displays 00000123, append "x" to get 123x, because it's still really a number.
Probably TMI, though!
This is the code I have created to resolve this issue:
Public Sub Change_10_Digit()
'----------------------------------------------------------------------------
' Change numeric loan number ot a 10 digit text number
' 2010-05-21 by Jamie Coxe
'
' Note: Insure exracted data Column is formated as text before running macro
'----------------------------------------------------------------------------
Dim Lastrow As Long
Dim StartRow As Long
Dim Col As String
Dim RowNum As Long
Dim nCol As String
Dim Loan As String
Dim Digit_Loan As String
Dim MyCell As String
Dim NewCell As String
Dim Cell_Len As Long
Dim MyOption As Long
'----- Set Options -------------------------------------------------------
MyOption = 2 '1 = place data in new column, 2 = Replace data in cell
StartRow = 2 'Start processing data at this row (skip header row)
Col = "B" 'Loan number in this colmun to be changed to 10 digit
nCol = "G" 'New column to place value (option 1 only)
'----- End Option Setings ------------------------------------------------
'Get last row
Lastrow = Range(Col & "65536").End(xlUp).Row
For RowNum = StartRow To Lastrow
'Combined Column and Row number to get cell data
MyCell = Col & RowNum
'Get data in cell
Loan = Range(MyCell).Value
'Change data in cell to 10 digit numeric with leading zeros
Digit_Loan = Format(Loan, "0000000000")
If My0ption = 1 Then
'Option 1 enter value in new cell
NewCell = nCol & RowNum
Range(NewCell).Value = Digit_Loan
Else
'Option 2 replace value in cell
Range(MyCell).Value = Digit_Loan
End If
Next RowNum
End Sub