VBA: preceding zeros dropped when copied over - vba

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

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

Excel VBA - Column count using variants

I have searched the forums but I am really struggling to get part of my code to work. Basically the idea is to search sheet 1 and copy one or more columns depending on the criteria to a specific worksheet.
i.e. if sheet 1 columns 1 and 3 contain "copy 01" then copy both columns to a sheet 2 and if sheet 1 columns 2 and 4 contain "copy 02" then copy both columns to a sheet 3 etc.
I can count rows fine using the code, but can't count columns. Seems to relate to not fiding the column range but I have no ideas to fix this! Any help would be much appreciated.
'Row
Dim NR As Long
Dim d As Variant
d = ws1.Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value
For NR = 1 To UBound(d, 1)
'column
Dim NC As Long
Dim e As Variant
e = ws1.Range(Cells(1, Columns.Count).End(xlToLeft).Column).Value
For NC = 1 To UBound(e, 1)
Thanks,
Stewart
You want this:
e = range("A1:" & split(cells(1,cells(1,columns.Count).end(xlToLeft).column).address(true,false), "$")(0) & "1").Address
The cells(1, columns.count).end(xlToLeft).column) gets the last column number (for example 13 for 'M').
Putting this into cells(1, lastcolNum) gets a cell that represents the cell in the first row of this column (for example Cell M1).
The address(true, false) method gets the cell reference with a dollar sign before the row but not before the column letter (for example "M$1"
The split function returns an array which splits the input string by the "$" character (for example array - ("M","1")
The (0) returns the 0th element in the returned array (for example "M")
Then putting this into the range function returns the range (for example) "A1:M1"
I'm not entirely sure what you're trying to do with the UBound function here. It would make more sense to make
e = cells(1,columns.count).end(xlToLeft).column
and then loop through
For N = 1 To e
As this will loop through each column.

Paste cells in specific row based on column header

I am not a programmer but would appreciate some help!
I am trying to take a range of cells, and paste them in another part of the spread sheet but in the correct column that I want (the column will change later that's why I want it to identify the column to paste the cells into the right row)
Example, take cells (A2:A10) and paste them into the "TTM" column D4:D12... where I have put the text TTM into D1... later, TTM may become E1, in which case the A2:A10 cells need to be moved to E4:E12...
Thanks a lot!
The following Function can be used to do what you want. You will need to explain what will trigger this code and if you want to search other than the 'Active Sheet'
Function Move_Cells()
Dim iCols As Integer
Dim i As Integer
Dim strKey As String
Dim iNewCol As Integer
strKey = "TTM" ' Set this to whatever label you want to search row 1 for.
iCols = ActiveSheet.UsedRange.Columns.Count ' Get count of used columns
For i = 1 To iCols ' Find column containing 'TTM'
If LCase(Cells(1, i).text) = LCase(strKey) Then ' ignore case inCASE SoMeBody....
iNewCol = i ' Save col # containing search keyword
Exit For
End If
Next i
'ActiveSheet.Range("A2:A10").Copy ' Where to copy from
'ActiveSheet.Cells(2, iNewCol).PasteSpecial xlPasteValues ' Paste into new location
'Application.CutCopyMode = False
' Try the following instead of the previous copy/paste
Range("A2:A10").Select
Selection.Copy
Cells(2, iNewCol).Select
ActiveSheet.Paste
End Function

How to look for values with % in a column and then sum them up and place it in an empty row?

I was wondering if there is any method that could detect a column with %? After that, sum the rows that have the %?
For example, in the following, i have a picture, Column B -D has values that contents %. The total % in B will be 130%, C will be 105%, D will be 90%. The total will be place at the subsequent empty row, for this particular example, will be row 8. I need the row to be flexible as it may end up more than 8.
I hope someone understands what i'm trying to convey here. What i'm trying to do is to look for the % and sum them up, the total will be placed at the subsequent empty row.
I do not understand the follow-up question about percentages in column 1. The following is my solution to your original question. It creates a row below any existing rows containing the total of any percentages in the column. I have formatted the values and have coloured then blue to show how. I have included comments saying what I am doing but not explaining why a statement does what it does. Try VBA Help first then come back with any questions.
Option Explicit
Sub SumPercentages()
Dim ColCrnt As Long
Dim ColCrntMax As Long
Dim ColMax As Long
Dim RowCrnt As Long
Dim RowCrntMax As Long
Dim RowSum As Long
Dim TotalPerc As Double
With Sheets("Sheet1") ' Replace with name of your sheet
' Find the last used row plus one as the row on which to place
' the totals. Warning, this statement will throw an error if
' there is a value on the last possible row.
RowSum = .Cells.SpecialCells(xlCellTypeLastCell).Row + 1
' Find the last used column
ColMax = .Cells.SpecialCells(xlCellTypeLastCell).Column
' Examine every used column
For ColCrnt = 1 To ColMax
' Find the last used row in this column
RowCrntMax = .Cells(Rows.Count, ColCrnt).End(xlUp).Row
TotalPerc = 0
' Examine each row of this column
For RowCrnt = 1 To RowCrntMax
If Right(.Cells(RowCrnt, ColCrnt).NumberFormat, 1) = "%" Then
TotalPerc = TotalPerc + Val(.Cells(RowCrnt, ColCrnt).Value)
End If
Next
' Save the value, format as percentage, colour blue
With .Cells(RowSum, ColCrnt)
.Value = TotalPerc
.NumberFormat = "0%"
.Font.Color = RGB(0, 0, 255)
End With
Next
End With
End Sub

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.