Excel VBA - Convert string entered in user form to number - excel

I have an excel user form into which the user enters numbers, when those numbers are entered into the spreadsheet they appear with the notification that this is a number stored as text. =SUM(H6:H13) shows a zero result.
I have tried NumCrtn = cLng(NumCrtn) - doesn't change the cell to a number, formula still shows zero.
I have tried NumCrtn = Val(NumCrtn) - doesn't change the cell to a number, formula still shows zero.
I have tried copy and paste.special to a value and that doesn't change it to a number either.
Don't know what to do.
Help!

Try this one:
With Range("H6:H13")
.NumberFormat = "0"
.Value = .Value
End With
Edit:
Another solution. Building on Pradeep Kumar's suggestion which deals with preparing your range before you enter the data, Change your code to something like this
Private Sub UserForm_Initialize()
Dim aCell As Range
Range("H6:H13").NumberFormat = "0"
'This is to cater for any previous values if filled in
For Each aCell In Range("H6:H13")
aCell.Formula = aCell.Value
Next
End Sub
Private Sub CommandButton1_Click()
'Entering value for H6
Range("H6").Value = TextBox1.Value
End Sub

Range("H6:H13").NumberFormat = "#,##0"

It is not a VBA solution, but an ordinary Excel solution.
Do like this
Select the column
Select Data - Text to columns
Quite often the default settings will do and you can click Finish. Otherwise you
will have to make sure that the result is just a "General" column
A macro doing just this would look something like this:
Columns("A:A").TextToColumns
There's a lot of parameters to the TextToColumns method, but it should work fine with default values only (i.e. no parameters).

Related

Macro to work on selected columns, not set columns (text to number)

i'm sure this is simple, but i'd like to know how to have a macro work only on a column that is selected (prior to running the macro)
the ultimate goal is to convert text to numbers, but the column these values are in are not always in the same column, without converting the entire workbook, it would only need to convert the selected column.
If I understand correct, you can try this.
a = ActiveCell.Column
Columns(a).Select
Selection.NumberFormat = "#,##0.00"
I found an answer that works using:
Sub change_txt_2_number()
With Selection
.NumberFormat = "0"
.Value = .Value
End With
End Sub

Printing out ActiveCell value on VBA

I'm trying to make a button which on click will print out the value of a cell as a string and not the appearance of the cell itself (if that makes sense) using the .PrintOut method in VBA. That cell is the active cell, whose value I set based on the cell next to it. Here is my code:
Sub Graphic2_Click()
Dim MyNumber as Integer
MyNumber = ActiveCell.Offset(-1, 0) + 1
ActiveCell.Value = MyNumber
ActiveCell.Printout
End Sub
I also tried MyNumber.PrintOut but I get an "Invalid Qualifier" error.
Am I missing out something too simple?
Please, try the next code. It use a temporary 'helper cell' where the format to be pasted (and recuperated after printing out):
Sub Graphic2_Click()
Dim helperCell As Range
With ActiveCell
.value = CLng(Offset(-1, 0)) + 1
Set helperCell = .Offset(1) 'it may be any cell to temporarilly be used
.Copy
helperCell.PasteSpecial xlPasteFormats
.ClearFormats
.PrintOut
helperCell.Copy
.PasteSpecial xlPasteFormats: helperCell.ClearFormats
End With
End Sub
To literally print just the contents of the cell:
Clear number formatting for the specified cell
Autofit column width for that column
Turn off gridlines
Turn off row and column headings
Set print area to the single cell, dismissing any warnings
Print out the active sheet
Each of these are straightforward to do in VBA, and probably straightforward to research on SO anyway.
You may also consider a mechanism to return the changed settings to their initial states afterwards. This would involve pushing (storing) the initial state to a variable or variables first, and popping (restoring) it back afterwards.
Explanation:
The VBA method .PrintOut is something you do to a worksheet, not a cell or its contents. Therefore, to get what you need, you need to set up the worksheet for printing so that the only thing that will appear is the contents of your chosen cell. This is what the above steps do.
For more information about the .PrintOut method, see:
https://learn.microsoft.com/en-us/office/vba/api/excel.sheets.printout
Or, to continue what the OP tried:
You could try something like:
ActiveCell.Formula = Range(ActiveCell.Offset(-1,0)).Value2 + 1
If this does not work, try:
ActiveCell.Formula = Range(ActiveCell.Offset(-1,0).Address).Value2 + 1
Or try these without the + 1 on the end, to verify that the rest of the formula is working the way you want it too. As mentioned, you may get a type mismatch issue causing an error if you don't trap first for whether the referenced cell contains a number.
.Formula in this example is how I am setting the content of the cell, and it can be used even when setting a value not necessarily literally a formula. You could use Value instead if you prefer.
.Value2 is a robust method of extracting the evaluated content of the source cell, as a value instead of as a formula.
The PrintOut method is to print a worksheet, not a range or single cell.
Note: This answer is not tested, as I am not near Excel right now.
Also... it's possible that there could be much simpler ways to do what you are trying to accomplish. Could you provide a bit more detail about the context of what you are trying to do.

If a cell is formatted as text, the formulas are not calculated

I need to keep the cells formatted as text and at the same time make sure that Excel calculates the formulas within them.
Is there a way to do it?
Embed your excel-formulas in the text-function.
=Text(your function,"#")
more info:
https://support.office.com/en-us/article/text-function-20d5ac4d-7b94-49fd-bb38-93d29371225c
edit: If your formulas are not being evaluated, then there can also be other causes for that than the cell-formatting.
I'm solved it!!!
In a Sheet module:
Option Explicit
Private Busy As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Busy Then
Busy = True
If ActiveSheet.ProtectContents Then ActiveSheet.Protect UserInterfaceOnly:=True
CalculateFormula Target.Row, Target.Column
Busy = False
End If
End Sub
In a standard module:
Option Explicit
Sub CalculateFormula(Row As Long, Column As Long)
Dim Format As String
If Left(Cells(Row, Column).Value, 1) = "=" Then
Format = Cells(Row, Column).NumberFormat
Cells(Row, Column).NumberFormat = "General"
On Error Resume Next
Cells(Row, Column).FormulaLocal = Cells(Row, Column).Value
On Error GoTo 0
Cells(Row, Column).NumberFormat = Format
End If
End Sub
It is unclear if you just need the format of the cell to be text, or if your need the results of a formula in a cell to be converted to a string/text. Excel formulas do no affect cell formatting, nor or are they affected by cell formatting. a perfect example of this is dates. Dates are really an integer counting the number of days since a start point. Day 1 is 1900/01/01 on a pc (On a mac I think its 1905/01/01 but could be wrong). If you enter today's date (2018/09/17) in any default cell, Excel identifies it as a date, changes the formatting of the cell and converts the date to 43360. You will see this if you change the cell format back to general and you will note that the number is right aligned. If you change the format of the cell to text, you will still see 43360 but instead it will be left aligned. More importantly its still a number and you can test it by using ISTEXT(A1) where A1 is the cell in question. It will still return true.
In order to make the contents of a cell a string, you can simply concatenate your formula with "".
=Your_Function&""
=1+1&""
Having said that. If a cell is formatted as a string, the FORMAT of the cell will remain a string despite whatever math calculation goes on inside it. So if you format A2 as text, and then place =1+1 inside it, the result in the cell will be the number 2 and the cell will be formatted as text.

VBA Excel Function to Set the Calling Cell .NumberFormat Property

I created this function and it works to put the value into the cell but it doesnt work to set the .NumberFormat property.
Public Function NewYears(year As Integer)
'Determine the cell that called the function
Dim rng As range
Set rng = ThisWorkbook.Sheets("How-To").range(Application.Caller.Address)
MsgBox rng.Address
fxFormat = "[$" & holidayName & "]"
NewYears = DateSerial(year, 1, 1)
rng.NumberFormat = fxFormat
End Function
Update For more information:
I will be having functions like =NewYears() that returns a date.
I will do this for any number of holidays. I would like to format the field where it still stores the date but the .NumberFormat property has the name of the holiday
So =NewYears() would return "01/01/2014" but in the sheet it would appear as "New Years"
Use the Worksheet_Change event:
Private Sub Worksheet_Change(ByVal Target As Range)
Target.Interior.ColorIndex = 39
Target.NumberFormat = "mm/dd/yyyy"
End Sub
Put this code in the Sheets("How-To") code module. Modify to whatever color/etc that you want to format.
When you initially enter the function in the cell, it will trigger the change event and this subroutine will execute.
Per Gary's comments (below), recalculation of existing formula will not trigger this event.
Functions can only return values or manipulate Comments, they can't modify formats directly.
How many calculations are in your sheet/book?
Are the cells in a particular arranged column or everywhere or Random?
If answer is Yes to first question I wouldn't suggest a volatile function triggers, well no one should. And things you do next depends on the answer to 2nd question.
Why dont you try "conditional formatting" though it could be a bit costly. Else if the Year cell should be in an organized column or cell make sure its format is ready-made to date.... if none of these apply, you may give us a better picture if your sheet's structure/design...

Excel VBA Time Format as decimal with Combobox

Very basic, and very annoying, I have searched solution for many hours with no help...
Problem: I'm populating Combobox from named range, range is list of times (formatted as time :-), Combo seems fine, drop-down shows my times as they should be, but when selected time is formatted as a decimal number...
Here is the code (ripped down to bare minimum):
Private Sub UserForm_Initialize()
ComboBoxTime.RowSource = "Help!Time"
End Sub
"Help" is name of worksheet containing named range "Time"I have tried formatting different ways with no luck...
ComboBoxTime = Format(ComboBoxTime, "hhmm")
Here is link to sample. http://www.equstom.fi/dateproblem.html
(And yes I need to populate from named range, instead for each loop, and I will set .value with code, Whole document is actually quite complex, but I included just The problem part...)
Try something like this:
Private Sub ComboBox1_Change()
With ComboBox1
.Value = Format(.Value, "hh:mm:ss AMPM")
End With
End Sub
HTH!
Edit
This is what I see when leaving your combo. The time display works OK.
Edit 2
Found the error "invalid property":
You must set "Match Requiered" to FALSE in the combo box. If you consider that it should be "TRUE" you will have to validate by hand ...
The problem is named range I'm using, when values are formatted as time it won't work. I got it to work if values were Text! Problem has something to do with excel being in Finnish and VBA in english...
I added second column next to range which copies text values to this named second range formatted as time. Quick and Dirty! (Thanks for your input Belisarius)

Resources