Excel VBA dividing 2 by 60 - vba

Have you ever noticed a problem dividing 2 / 60 in Excel Vba code? I am using Excel 2013. Please test the code below:
Sub test1()
Dim A As Integer
Dim B As Integer
MsgBox 2 / 60
A = 2
B = 60
MsgBox A / B
End Sub
Sub test2()
Cells(1, "a") = 2
Cells(1, "b") = 60
Cells(1, "c") = Cells(1, "a") / Cells(1, "b")
MsgBox Cells(1, "a") / Cells(1, "b")
End Sub
Test1 will generate a wrong answer for the math operation. Result should be 0,0333333, but it brings 3,3333333E-02. Test2 works with cells and it brings correct result.
What is wrong with my code? Is it a bug? I am soooo intrigued, why can't vba do the right calculation?
Thanks for the help

In number part E+XX or E-XX, XX denotes how many digits the decimal point is shifted right or left.
So in your 3.333333E-02 shift the decimal point 2 places left and you get 0.03333333
One of the points of such a notation is to spare you from zeros (0.0000012345 = 1.2345E-06) and to correctly show you only digits which are within the number precision (hypthetical 1234567890123456789 = 1.2345678E+18 (rest of digits is 'clipped').
And 5E+00 = 5 :) no shift.
More information: E notation

Related

For loop and If statement Excel VBA

I would really appreciate if you could help me out with this problem. I am trying to get vba to provide me all the numbers in increment of 1 from 1 to a value in cell G1 and populate it into column C. Afterwards, I want vba to check each cell in column C starting from C1 to see if the value is greater than a number and to populate into the column next to it( Column D1 onwards )
For example, cell G1 has the number 5.
So, I should see the following in column c , which are the 1, 2,3,4,5 and in column D I should see only the value for cells greater than say 3. So that means only the value 4, and 5 is populated in columnn D.
I would appreciate any help as I am quite new to VBA and am trying to get a hang of it.
Thnx.
Give this a try:
Sub elyas()
Dim i As Long, MagicNumber As Long
Dim k As Long
MagicNumber = 3
k = 1
For i = 1 To [G1]
Cells(i, "C").Value = i
If i > MagicNumber Then
Cells(k, "D").Value = i
k = k + 1
End If
Next i
End Sub

the curious case of disappearing decimals

I have an issue with disappearing decimal places when I put them into arrays and then pasting them out again. not sure why this is happening at all. any soluntions?
an example below:
excel:
A B
1 Input $213,213,132,135,654.00 <--format: Accounting
2 =B1/1000000 $213,213,132.14 <--format: Accounting
3 output $213,213,132,135,700.00 <--format: Accounting
Code:
Sub test()
Dim ar() As Variant
ReDim ar(1)
ar(1) = Cells(2, 2).Value
ar(1) = ar(1) * 1000000
Cells(3, 2) = ar(1)
End Sub
213213132135654.00 / 1000000 = 213213132.135654
You provided the answer when you mentioned that it only does it when formatted as accountancy. Accountancy works to four decimal places only making the result 213213132.1357, when when multiplied gets to the non-matching 213213132135700.00.
As to a fix, I would suggest either using rounding to 4 decimal places in all formula or do the math in another worksheet as numbers and then present the results on your main worksheet as accountancy.

Removing loops to make my VBA macro able to run on more data

in my data there are more than a thousand different six digit numbers that are reoccurring in no specific pattern. I need to find all six digit codes that exist in column A and for each number. For example 123456, then find summarize the value in column B for every row that has 123456 in column A. My code is not very effective but the runtime is not a problem if I run with only 10 rows. However, in the real data sheet there are 80 000 rows and my code will take to much time. Can someone help me edit my code but removing certain loops within loops or some stop conditions. I'm new to VBA and can't do it myself in the limited time I have.
Sub Test2()
Dim summa As Long
Dim x As Long
Dim condition As Boolean
Dim lRows As Long
Dim k1 As Integer
Dim i As Long
x = 1
Worksheets("Sheet1").Activate
For i = 100000 To 999999
k1 = 1
lRows = 10
condition = False
While k1 <= lRows
If Cells(k1, "A").Value = i Then
condition = True
End If
k1 = k1 + 1
Wend
If condition = True Then
Cells(x, "F").Value = Application.SumIf(Range("A:A"), CStr(i), Range("B:B"))
Cells(x, "E").Value = i
x = x + 1
End If
Next i
MsgBox "Done"
End Sub
You don't need VBA for this task. Follow these steps.
Insert a blank column C in a copy of the original data sheet.
Insert a SUMIF formula, like =SUMIF(A:A, A2, B:B) in C2 and copy all the way down.
Now all items 123456 will have the same total in column C
Copy column C and Paste Values (to replace the formulas with their values).
Delete column B.
Remove duplicates.

Excel VBA: Find first value in row larger than 0 and sum over following 4 cells

As a complete beginner to VBA Excel, I would like to be able to do the following:
I want to find the first value larger than 0 in a row, and then sum over the following 4 cells in the same row. So
Animal1 0 0 1 2 3 0 1
Animal2 3 3 0 1 4 2 0
Animal3 0 0 0 0 0 1 0
Results in
Animal1 7
Animal2 11
Animal3 1
Is this possible?
(Your problem description didn't match your examples. I interpreted the problem as one of summing the 4 elements in a row which begin with the first number which is greater than 0. If my interpretation is wrong -- the following code would need to be tweaked.)
You could do it with a user-defined function (i.e. a UDF -- a VBA function designed to be used as a spreadsheet function):
Function SumAfter(R As Range, n As Long) As Variant
'Sums the (at most) n elements beginning with the first occurence of
'a strictly positive number in the range R,
'which is assumed to be 1-dimensional.
'If all numbers are zero or negative -- returns a #VALUE! error
Dim i As Long, j As Long, m As Long
Dim total As Variant
m = R.Cells.Count
For i = 1 To m
If R.Cells(i).Value > 0 Then
For j = i To Application.Min(m, i + n - 1)
total = total + R.Cells(j)
Next j
SumAfter = total
Exit Function
End If
Next i
'error condition if you reach here
SumAfter = CVErr(xlErrValue)
End Function
If your sample data is in A1:H3 then putting the formula =SumAfter(B1:H1,4) in I1 and copying down will work as intended. Note that the code is slightly more general than your problem description. If you are going to use VBA, you might as well make your subs/functions as flexible as possible. Also note that if you are writing a UDF, it is a good idea to think of what type of error you want to return if the input violates expectations. See this for an excellent discussion (from Chip Pearson's site - which is an excellent resource for Excel VBA programmers).
ON EDIT: If you want the first cell greater than 0 added to the next 4 (for a total of 5 cells in the sum) then the function I gave works as is, but using =SumAfter(B1:H1,5) instead of =SumAfter(B1:H1,4).
This is the one of the variants of how you can achieve required result:
Sub test()
Dim cl As Range, cl2 As Range, k, Dic As Object, i%: i = 1
Set Dic = CreateObject("Scripting.Dictionary")
For Each cl In ActiveSheet.UsedRange.Columns(1).Cells
For Each cl2 In Range(Cells(cl.Row, 2), Cells(cl.Row, 8))
If cl2.Value2 > 0 Then
Dic.Add i, cl.Value2 & "|" & Application.Sum(Range(cl2, cl2.Offset(, 4)))
i = i + 1
Exit For
End If
Next cl2, cl
Workbooks.Add: i = 1
For Each k In Dic
Cells(i, "A").Value2 = Split(Dic(k), "|")(0)
Cells(i, "b").Value2 = CDec(Split(Dic(k), "|")(1))
i = i + 1
Next k
End Sub
Here is what I would use, I dont know any of the cell placement you have used so you will need to change that yourself.
Future reference this isnt a code writing site for you, if you are new to VBA i suggest doing simple stuff first, make a message box appear, use code to move to different cells, try a few if statments and/or loops. When your comftable with that start using varibles(Booleans, string , intergers and such) and you will see how far you can go. As i like to say , "if you can do it in excel, code can do it better"
If the code doesnt work or doesnt suit your needs then change it so it does, it worked for me when i used it but im not you nor do i have your spread sheet
paste it into your vba and use F8 to go through it step by step see how it works and if you want to use it.
Sub test()
[A1].Select ' assuming it starts in column A1
'loops till it reachs the end of the cells or till it hits a blank cell
Do Until ActiveCell.Value = ""
ActiveCell.Offset(0, 1).Select
'adds up the value of the cells going right and removes the previous cell to clean up
Do Until ActiveCell.Value = ""
x = x + ActiveCell.Value
ActiveCell.Offset(0, 1).Select
ActiveCell.Offset(0, -1).ClearContents
Loop
'goes back to the begining and ends tallyed up value
Selection.End(xlToLeft).Select
ActiveCell.Offset(0, 1).Value = x
'moves down one to next row
ActiveCell.Offset(1, 0).Select
Loop
End Sub

excel vba anomaly (for loop result) [duplicate]

This question already has an answer here:
Why is 134.605*100 not equal 13460.5 in VBA Access? [duplicate]
(1 answer)
Closed 8 years ago.
Sorry for not giving more detailed title, but it is because of this special case. My google search did not give me any similar topic.
The following simple code should give a series of numbers from 0.1 to 10 with step 0.1 (I hoped at least) in column A:
Cells(1, 1) = 0.1
For i = 2 To 100
Cells(i, 1) = Cells(i - 1, 1) + 0.1
Next i
Until 5.9 it works well, but after that the result is not as expected:
instead of 6 I get 5,99999999999999
instead of 6.1 I get 6,09999999999999
instead of 6.2 I get 6,29999999999999
...
Could anyone explain what is wrong with the code or why I get this result?
Thanks!
Or simply this?
Sub Sample()
Dim i As Long
For i = 1 To 100
'~~> Change Sheet1 to respective sheet
ThisWorkbook.Sheets("Sheet1").Cells(i, 1) = i * 0.1
Next i
End Sub
Or like this
Sub Sample()
'~~> Change Sheet1 to respective sheet
With ThisWorkbook.Sheets("Sheet1").Range("A1:A100")
.Formula = "=Row()*.1"
.Value = .Value
End With
End Sub