Excel VBA Won't Keep Leading Zeroes - vba

I can't seem to find a way to save leading zeros in my VBA code. The zeros are necessary since they correspond to unique IDs.
I've tried changing the number format to text and 0000.... in excel and the same approach in my actual code:
ActiveSheet.Cells(i, j).NumberFormat = "00000"
Any other suggestions? (If I manually type these numbers into VBE it strips the leading zeros too).
EDIT:
Sheets.Add.Name = "Temp"
Sheets("Sheet1").Select
ActiveSheet.Cells(2, 2).NumberFormat = "000"
cid = Cells(2, 2)
MsgBox cid
Sheets("Sheet2").Select
ActiveSheet.Cells(6, 1).NumberFormat = "00000"
sid = Cells(6, 1)
Sheets("Temp").Select
Url = _
"URL;" & _
"http......asp?" & _
"X1=" & cid & "&" & _
"X2=" & sid & "&"
This is inside a loop ultimately but I'm debugging as individual iterations.

All below deliberations were about writing to a cell, not reading from it. Changing the Numberformat doesn't work that way.
See if you can figure out how this code works:
dim v as integer
v = val(Sheets("Sheet1").Cells(2, 2))
dim cid as string
cid = format(v, "000")
You should never use Select and ActiveSheet that way, it is not necessary; and never use Cells without the sheet it should be referring to.
(Val can be omitted if the cell is really already numeric and not text).
Earlier answer... :
This code works perfectly fine for me
Worksheets(1).Columns("A").NumberFormat = "#"
Worksheets(1).Cells(1, "A").Value = "00023"
And also does
Worksheets(1).Columns("A").NumberFormat = "000000"
Worksheets(1).Cells(1, "A").Value = "0023"
(Here the string is converted to a number and displayed with 6 digits)
EDIT:
If that fails - although I could not explain that - I'd still bet that the ' should really work:
(No numberformat required.)
Dim s As String
s = "0002"
Worksheets(1).Cells(1, "A").Value = "'" & s

Setting the format to text or "00000" should work. The small snippet below gives the results expected. With the first storing a value of 0001 and the second storing a value of 1 that is formatted to look like 0001.
This also works if the cell value was stored in a string variable.
Sub set_value()
Range("A1").NumberFormat = "#"
Range("A1").Value2 = "0001"
Range("B1").NumberFormat = "0000"
Range("B1").Value2 = "1"
End Sub

Related

Works with long type, but not with any other variable type

This is the code, that is bug-free:
Sub Minus()
Dim cell As Long
cell = ActiveCell.Value
Dim offsetcell As Long
offsetcell = ActiveCell.Offset(0, -1).Value
ActiveCell.Formula = "=" & cell & "-" & offsetcell
End Sub
As soon as I change the variable to any other type (preferably Double) the code stops working and bug appears in the concatenated function below.
Any ideas why?
i would like full original value minus adjacent cell (one left).
You are probably casting a decimal comma to text which will break the formula. So, convert using Str that will return a dot as the decimal separator:
ActiveCell.Formula = "=" & Str(cell) & "-" & Str(offsetcell)
That works here.
PS: Don't use native object names (cell) as the name for variables holding completely different values types.

How to put a VBA formula using dynamic variables capturing Address?

I am running a Loop to capture the start of Range and end of Range for a particular scenario. After I find my start range and end range, I want to put it as a formula in a cell. For example:
Cells(1,1).Formula "= Min( startrange:endrange)"
The above code has assumed the variables as text and instead of putting the cell address these variables are handling, it is pasting the formula as text like this : '= Min( startrange:endrange)'
I have no idea and have tried different approaches I could get from internet like below
' cells(4,4).formula = "=Min("&startrage& :"" & endrange & ")""
' Cells(4, 4).Formula = "=Min(startrange.value :endrange)"
'Cells(4, 4).Formula = Application.WorksheetFunction.Min(startrange:endrange)
' Cells(4, 4).Formula = "=Min("&startrange&"&":"& " &endrange&")"
where
startrange = ActiveCell.Offset(1, 3).Address(0, 0)
endrange = ActiveCell.Offset(0, 3).Address(0, 0)
Nothing works.
How can I achieve this? Specially I am also facing error in handling ":".
cells(4,4).formula = "=Min(" & startrage & ":" & endrange & ")"

Excel VBA - if/then statement - Identifying cells with a dash

I am trying to write a VBA line where if cell A1 contains a dash anywhere in the cell, then B1 will say "Blue". If there is no dash, then B1 would say "Red".
I have the following code written, but it's not working and I'm not sure if I'm doing the "like" part correctly:
ActiveCell.FormulaR1C1 = _
"=IF(RC[-1]=" - ",""Blue"",""Red"")"
Thank you for any help you can provide! I've done so much searching, but have been unable to find any examples that didn't include specific numbers or text.
You can also use
ActiveCell.FormulaR1C1 = "=IF(ISNUMBER(FIND(""-"",RC[-1])),""Blue"",""Red"")"
Or a one-liner:
ActiveCell.FormulaR1C1 = "=IF(ISERROR(FIND(""-"",RC[-1])),""Red"",""Blue"")"
You could do it with a simple VBA script like this:
Sub Test()
Dim sh1 As Worksheet
Set sh1 = Sheets("Sheet1")
Application.ScreenUpdating = False
For x = 1 To sh1.Cells(rows.Count, "A").End(xlUp).Row
If InStr(1, sh1.Range("A" & x).Value, UCase("-"), 1) > 0 Then sh1.Range("B" & x).Value= "Red"
If InStr(1, sh1.Range("A" & x).Value, UCase("-"), 1) < 0 Then sh1.Range("B" & x).Value = "Blue"
Next x
Application.ScreenUpdating = True
End Sub
I don't believe that put a formula in every "B" column cells it's a good pratice, Excel can take a long time to calculate.
Try this:
Sub Example()
mySheet.Cells(1, "B").Value = IIf(Not InStr(1, mySheet.Cells(1, "A"), Chr(45), vbTextCompare) = 0, "Blue", "Red")
End Sub
You can loop through every cell you want to put that condition using this code.
Functions:
IIf is equals to Excel Worksheet Function "IF".
InStr search a string in another string, you can pass a unique char as criterea. I used chr(45) because it returns a char according to the passed code, 45 references to Dash code.
The error, corrected (but not pointed out) in several of the other answers lies in changing your formula from
" - "
to
"" - ""
i.e. going from single double-quotes around your - to double double-quotes. The single quote is ending your string - you can even see that the - shows up in black text in your question instead of red text, therefore, it's not part of the string being inserted into ActiveCell.FormulaR1C1.

How to remove spaces from an entire Excel column using VBA?

I'm trying to delete the spaces that I have in each field of the column "A" this spaces are at the end of the string some of the string has 3 spaces others 4. When I run the code, I don't have error, so I think I have a bug because nothing happened when is running.
Dim result As String
Last = Cells(Rows.Count, "A").End(xlUp).Row
For i = Last To 1 Step -1
If (Right(Cells(i, "A").Value, 4)) Like " " Or (Right(Cells(i, "A").Value, 3)) Like " " Then
result = Replace(Cells(i, "A"), " ", "")
End If
Next i
In your specific case, the problem is that you're storing the replacement value in a string variable named result, then doing nothing with it. If you want it to be in the Cell, you have to add it back in there, such as:
Cells(I, "A").Value = result
Keep in mind, there is an Application.Trim method that can actually save a bit of time over looping. Experiment with code such as:
Dim rng as Range
set rng = Range("A1:A10")
rng.Value = Application.Trim(rng)
Currently you are not actually updating the cell in the loop, you just;
result = Replace(Cells(i, "A"), " ", "")
You should:
Cells(i, "A") = Replace(Cells(i, "A"), " ", "")
Or better
Cells(i, "A") = rtrim$(Cells(i, "A"))
Which will remove all right spaces. You can probably remove the if check as well.
What are expecting this code to do? as currently the values are being read into result. It would also be better to use trim to remove trailing spaces.
Dim result As String
Last = Cells(Rows.Count, "A").End(xlUp).Row
For i = Last To 1 Step -1
result = RTrim(Cells(i, "A"))
Next i

VBA for Excel - building .Formula with contents containing quotation marks

I'm coding a project in VBA for Excel, which loops to a file, matches the 'code' for each of the quantities, and then feeds all the matches for that code to a user defined function, which goes onto the Excel sheet.
I can read the info, sort it so postdata(nr_of_datafield, nr_of_item) returns me the row in the source sheet on which the value is listed. Based on this, I need to create (through .Formula) a syntax like this:
=formul(raming!J104) (if there's only one occurence)
=formul(raming!J104;"+";raming!J108) (etc., always adding the same extra if there's multiple occurences)
=formul(raming!J104;"+";raming!J108;"+";raming!312;"+";raming!J403) etcetera, with always needing to get the previous values from what's already in Cells.Formula.
Based on this check:
Code:
Right(Workbooks(meetstaatfile).Sheets("HOR_raming").Cells(lusteller12, 9 + CInt(postdata(3, eerstepositie)) * 3).Formula, 2) = "()"
I can detect if there is already any contents added here. If not (meaning the check for () ending is positive), I replace with this:
Code:
Workbooks(meetstaatfile).Sheets("HOR_raming").Cells(lusteller12, 9 + postdata(3, eerstepositie) * 3).Formula = "=formul('raming'!J" & postdata(2, eerstepositie) & ")"
To create a formula that looks like: =formul(raming!J104)
(the '104' in this example is the output from postdata(2,eerstepositie)
However, if it doesn't trigger for the () ending, there already is a value, and I need to extend the formula to something like this: =formul(raming!J104;"+";raming!J108)
I've been trying to figure out how to do this by replacing ')' with the block I want added, but I cannot get it to work to input the quotation marks. ('formul' is very similar to concatenating text).
How can I make a variation of the codeline above that lets me alter the cell input? Either by a Replace() like I was trying, or reading what's between the formul() brackets and rebuilding the formula?
If you need to have quotation marks as content within a string literal in VBA, you have to double them. See: http://msdn.microsoft.com/en-us/library/ms234766.aspx
.Formula = "=formul('raming'!J" & 104 & ",""+""," & "'raming'!J" & 108 & ")"
Or with your postdata:
.Formula = "=formul('raming'!J" & postdata(2, eerstepositie) & ",""+""," & "'raming'!J" & postdata(2, whatevergets108) & ")"
I don't know, whether I have understood it right, but if you need to concatenate the formula in dependence of the contents of an array, then this can be achieved like so:
Sub test()
'one occurrence
postdata = [{0;104}]
sFormulaString = getFormulaString(postdata, 2)
MsgBox sFormulaString
'two occurrences
postdata = [{0,0;104,108}]
sFormulaString = getFormulaString(postdata, 2)
MsgBox sFormulaString
'three occurrences
postdata = [{0,0,0;104,108,312}]
sFormulaString = getFormulaString(postdata, 2)
MsgBox sFormulaString
End Sub
Function getFormulaString(postdata As Variant, nr_of_datafield As Long) As String
sFormula = "=formul("
For i = LBound(postdata, 2) To UBound(postdata, 2)
sFormula = sFormula & "'raming'!J" & postdata(nr_of_datafield, i) & ",""+"","
Next
sFormula = Left(sFormula, Len(sFormula) - 5) & ")"
getFormulaString = sFormula
End Function
Hm, or is the real need, to append new formula parts into an existing formula? If so, the following code will append a new part into the Formula in A1 every time it runs.
Sub test2()
postdata = [{0;104}]
sFormula = Range("A1").Formula
If sFormula = "" Then sFormula = "=formul("
If Right(sFormula, 1) = ")" Then sFormula = Left(sFormula, Len(sFormula) - 1) & ",""+"","
sFormula = sFormula & "'raming'!J" & postdata(2, 1) & ")"
Range("A1").Formula = sFormula
End Sub
Greetings
Axel