Convert numbers stored as text to numbers - excel

this code does not seem to work well always when copying currency data from another sheet:
Dim myprice As String
myprice = othersheet.Range("H" & c.Row).Value
ws.Range("C" & r).Value = myprice
ws.Range("C" & r).Style = "Currency"
sometimes cells have a warning that "this number is formatted as text"

Excel's "Number Stored as Text" issue can be a bit vexing.
The Help recommendation is to perform a conversion operation by multiplying the value by 1. In practice, however, you're probably better off checking that myprice is numeric and then proceeding accordingly.
For instance:
Dim myprice As String
myprice = othersheet.Range("H" & c.Row).Value
If IsNumeric(myprice) Then
myprice = CCur(myprice)
Else
'Catch non-numeric accordingly
myprice = "Couldn't convert to number"
End If
ws.Range("C" & r).Value = myprice
ws.Range("C" & r).Style = "Currency"
HTH

Try declaring myprice as a Currency.

Have you tried using NumberFormat of the cell
ws.Range("C" & r).NumberFormat = "$#,##0.00"

This is working for me:
For Each myprice In __your target range here__
myprice.Value = CDec(myprice.Value)
myprice.NumberFormat = "0.00" 'or whatever format you wish
Next myprice

This code worked for me, to convert cells depending on their contents. It ran fairly quickly for a worksheet with >800,000 cells containing numbers stored as text, with 32-bit Excel 2013 running on a Windows 8.1 machine. It did the job in less than 2 minutes.
For Each aCell In ThisWorkbook.Sheets("Working data").UsedRange.Cells
If aCell.Errors.Item(xlNumberAsText).Value Then
aCell.Formula = aCell.Text
End If
Next aCell

Related

Need macro to write the formula in a cell not the answer (ouput)

I cannot figure this out - I either get a Named? error or Application defined error on trying everything.
Dim sAmt As Integer
Dim sOriginalAmount As Integer
sOriginalAmount = ActiveCell.Value
sAmt = Application.InputBox("How much additional cost?", Type:=2)
ActiveCell.Formula = sOriginalAmount + sAmt
What I want Excel to do is write the formula in the cell not the output.
For example - Currently if I have sOriginalAmount as 15 and I enter sAmt as 20, on running the code, it gives the answer 35 in the cell, but I want it to write =sum(valueofsOriginalAmount + valueofsAmt) so that at a later time I can see what was the original amount and how much was added.
Can anyone please help? I have tried & "" in various combinations but I just can't get it. Apologies for such a noobie question, but I am self learned and I code for my work only.
This should work.
ActiveCell.Formula = "=" & sOriginalAmount & "+" & sAmt
Or if you actually want to use SUM.
ActiveCell.Formula = "=SUM(" & sOriginalAmount & "," & sAmt & ")"

Adding freshly created formula into new module

I've just created a brand new macro. Took function down below from internet (all credits goes to trumpexcel.com), code down below
Function CONCATENATEMULTIPLE(Ref As Range, Separator As String) As String
Dim Cell As Range
Dim Result As String
For Each Cell In Ref
Result = Result & Cell.Value & Separator
Next Cell
CONCATENATEMULTIPLE = Left(Result, Len(Result) - 1)
End Function
Then I proceed to extract data from various columns and into the one (my table is 20 rows x 10 columns)
Sub conact_data()
Dim i As Integer
For i = 2 To Cells(Rows.Count, "A").End(xlUp).Row
Cells(i, "M").Value = Cells(i, "A").Value & " " & _
Cells(i, "B").Value & " / " & Cells(i, "D").Value & "; "
Next i
End Sub
Thanks to that I've got combined data from column A, B and D, so its 20 rows. All I want to do now is to concatenate data from M2:M21 using CONCATENATEMULTIPLE function therefore I try various approach (I want this huge line in P2 cell) like :
Cells(2, 16).Value = CONCATENATEMULTIPLE (M2:M21, " ")
or
Range("P2") = "CONCATENATEMULTIPLE (M2:M21, " ")"
I don't really know how to apply that
Secondly, I'd like withdraw the Cells(i, "B").Value as percentage. Can I do that in one line like Cells(i, "B").NumberFormat="0.00%".Value (which is not working for me obviously) else I need to copy column B into another column with number format and then combine the new column, properly formatted instead of column B?
Thanks in advance
Percent format: Range("B" & i).NumberFormat = "0.00%"
CONCATENATEMULTIPLE
In VBA, CHR(32) = " "
In Excel, CHAR(32) = " "
With that being said...
'Value
Range("P2").Value = CONCATENATEMULTIPLE(Range("M2:M21"), CHR(32))
'Formula
Range("P2").Formula = "=CONCATENATEMULTIPLE(M2:M21, CHAR(32))"
You should really qualify all of your ranges with a worksheet
Say your workbook has 10 sheets. When you say Range("P2"), how do we (VBE) know what sheet you mean? Objects need to be properly qualified. Sometimes this is not a huge issue, but when you are working across multiple sheets, not qualifying ranges can lead to some unexpected results.
You can qualify with a worksheet a few ways.
Directly: ThisWorkbook.Sheets("Sheet1").Range("P2").Copy
Or use a variable like so
Dim ws as Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Range("P2").Copy
Now there is no room for ambiguity (potential errors) as to the exact location of Range("P2")
First of all, remove your ConcatenateMultiple() code, and instead use Excel worksheet function CONCAT(), which takes a range and a delimiter as parameters.
Here is how you can handle the percentage issue and supply a default for non-numeric items. I've also cleaned up the way you reference your data range.
Sub concat_data()
Dim rngRow As Range, vResult As Variant
Const DEFAULT = 0 'Can also be set to a text value, eg. "Missing"
For Each rngRow In [A2].CurrentRegion.Rows
If IsNumeric(rngRow.Cells(, 4)) Then vResult = rngRow.Cells(, 4) * 100 & "%" Else vResult = DEFAULT
Range("M" & rngRow.Row) = rngRow.Cells(, 1) & rngRow.Cells(, 2) & "/" & vResult & ";"
Next
[M2].End(xlDown).Offset(1).Formula = "=CONCAT(M2:M" & [M2].End(xlDown).Row & ",TRUE,"" "")"
End Sub
I'm not a fan of hard-coding range references, like the [A2] or Range("M"), but will leave that for another time.

Excel VBA macro reading one column with differing text

I was tasked with creating a code that will check to see if internal hyperlinks in an excel spreadsheet worked. This code first changes the formulas that were on the spreadsheet and makes them actual hyperlinks (they were originally formulas linking the locations together). The problem that I have now is that I want to create hyperlinks ONLY if Column S has text. If it doesn't, I don't want the "E-COPY" text to be displayed. All of the text in Column S varies (not one line has the same characters), which is why I'm drawing a blank is to how I tell the program to only continue if it has any text, not anything specific. I am working with Excel 2016.
Also, I am doing this to 71935 and counting rows; is there a limit to how many it can go through? If so, what can I do about it?
Thank you!
Sub CreateHyperlinks()
Dim FN As Variant
Dim Path As Variant
Dim count As Variant
Sheets(1).Activate
count = WorksheetFunction.CountA(Sheets(1).Range("A:A"))
For i = 2 To count
If Range("AM" & i).Value = "Yes" And Columns("S") = Then
Range("E" & i).Value = ""
Path = Sheets(1).Range("R" & i).Value
FN = Sheets(1).Range("S" & i).Value
Sheets(1).Range("E" & i).Select
Selection.ClearFormats
Selection.Hyperlinks.Add Anchor:=Selection, Address:=Path & FN, TextToDisplay:="E-COPY"
Range("AM" & i).Value = " "
End If
Next i
End Sub
If you just need to check for any content in ColS then:
If Range("AM" & i).Value = "Yes" And Len(Range("S" & i).Value) > 0 Then
Few things:
'make a reference to the sheet you're working with
Dim ws As Worksheet
Dim wb As Workbook
Set wb = Excel.Application.ThisWorkbook
Set ws = wb.Worksheets(1)
'gets the absolute last row with data in it // ignores empty cells
count = ws.UsedRange.Rows.Count
personally, i hate working with named ranges, so i would suggest setting range references like so
what you wrote
Path = Sheets(1).Range("R" & i).Value
what i believe it should look like
Path = ws.Cells(i, 18).Value
if you want to test the type when working with variants, try this:
'tests the type associated with the variant. an 8 = string
If VarType(ws.Cells(i, 19).Value) = 8 Then
'do your thing
'tests if the value is null
ElseIf VarType(ws.Cells(i, 19).Value) = 0 Then
'do your other thing
here's a list of the vartype enumeration to help you out.
hope it helps!

Copy Data from Cell A to B and convert to Number

The below code is copying the data fine, however the copy when then number is copied over is copied as text. Is there any way to copy it over as a number?
Worksheets(1).Range(destCol1 & LR & destCol2 & LR).cells(3).value = Split(srcRange(5).value)
I've tried recording a macro where I'd highlight the data and click the option "Convert text to number" but it's not recording the VBA for that part.
EDIT 1:
With Worksheets(1).Range(destCol1 & LR & destCol2 & LR)
.cells(1).value = srcRange(2).text
.cells(2).value = srcRange(1).value
.cells(3).value = CDbl(Split(srcRange(5).value)(1))
.cells(4).value = srcRange(6).value
End With
Untested:
Sub jdskfhs()
Worksheets(1).Range(destCol1 & LR & destCol2 & LR).Cells(3).Value = CDbl(Split(srcRange(5).Value))
End Sub
EDIT#1:
Here is what you need:
Sub jdskfhs2()
Worksheets(1).Range(destCol1 & LR & destCol2 & LR).Cells(3).Value = CDbl(Split(srcRange(5).Value)(1))
End Sub
This new code converts the second element of the Split()-generated array to a number.
After quite a bit of digging, I found another answer on these forums here
I would ideally like to have it all done it one line to reduce processing power as these pages can get quite large; unfortunately this was the best solution I could get.
EDIT:
Using the below code that I modified a bit, but it does work
Private Function TextToNumber(rng As Range)
LR = ActiveSheet.Range("C" & Rows.Count).End(xlUp).row
For R = LR To 3 Step -1
With rng.cells(R, 1)
.NumberFormat = "General"
.value = .value
End With
Next R
End Function

Concatenating SumIfs in VBA

I'm trying to get this segment of code to execute. This is a simplified version of the code. I've included the relevant code. I'm trying to concatenate strings and named ranges into a SumIfs formula, but I get error 1004 "Application-defined or Object-defined error." I have a working line of code above this problem section that is similar with the exception of doing a sum function, instead of sumif. Any idea how to get this code to execute? Thank you.
Dim wb As Workbook
Dim ara As Worksheet
Dim inv As Worksheet
Dim ARBlock As Range
Dim Invoices As Range
Dim AgedDays As Range
Set wb = ThisWorkbook
Set ara = wb.Sheets("AR Aging")
Set inv = wb.Sheets("Invoices")
Set ARBlock = ara.Range("a6")
Set Invoices = inv.Range("a6", inv.Range("a6").End(xlDown))
Set AgedDays = Invoices.Offset(0, 6)
'Populate A/R age buckets
For i = 6 To ARBlock.Rows.Count + 6
With ARBlock(i - 5, 1).Offset(0, 3)
.Value = "=SumIfs(" & Invoices.Offset(0, 4).Address & "," & _
Invoices.Address & "," & ARBlock(i - 5, 1).Value & "," & _
Invoices.Offset(0, 6).Address & ","" <= "" & &O30)"
End With
Next i
End Sub
The line beginning with ".value" is where I'm getting the error message. P.S.: I need the cell to contain the concatenated formula, as opposed to the output value.
UPDATE 1:
As some suggested I updated the .value line to:
.Offset(0, 3).Formula = "=SumIfs(Invoices.Offset(0, 4).Address,Invoices.Address,ARBlock.cells(i - 5, 1).Value)"
I'm still getting the same error. Some auditing I've done:
Removing the "=" before "Sumifs" allows the code to run fine; pasting in the formula into the target cell as text. In this form, my output for i=1 goes to ARBlock.cells(1,1), as it should.
I also used Debug.Print to view all of the components of the formula:
Debug.Print ARBlock.Cells(i - 5, 1).Address
'output $A$6
Debug.Print ARBlock.Cells(i - 5, 1).Value
' output International Business Machines
Debug.Print Invoices.Offset(0, 4).Address
'output $E$6:$E$255
Debug.Print Invoices.Address
'output $A$6:$A$255
I suspected the issue might be that the range dimensions might have been off, but this is not the case. My next suspicion is that the output International Business Machines needs to be in " " for the formula to read it correctly. I hardcoded in
""International Business Machines""
to see if this would fix the formula, but I keep getting the same error once I add the "=" back in. The formula syntax is correct, the dimensions are the same between the sum range and criteria range. Anyone else have any ideas?
.Offset(0, 3).Formula = "=SumIfs(Invoices.Offset(0, 4).Address,Invoices.Address,ARBlock.cells(i - 5, 1).Value)"
Change to:
.Offset(0, 3).Formula = "=SumIfs(" & Invoices.Offset(0, 4).Address & ", " & Invoices.Address & ", " & chr(34) & ARBlock.Cells(i - 5, 1).Value & chr(34) & ")"
EDIT: Added quotes chr(34) around your string!
Your ARBlock(i - 5, 1).Value most likely is an empty cell, which messes the SUMIFS formula as it builds it with to consecutive commas

Resources