WorksheetFunction.Sum with For loop - excel

Hi! I'm posting this question in the hope it hasn't already been answered!
As you can see in the image, I would like to get the area under the curve using VBA. The results of the trapezoid method using the simple formula (B4 - B3) * (C4 + C3) / 2 are given in the column E (light yellow shade) and the sum is given in the cell F4, which is the area I want.
To test wether my VBA code works, I limited it to calculate the sum of the first two trapezoids, but it gives me the surface of the second trapezoid instead:
Sub Integral()
Dim i As Integer
Dim Integral As Double
For i = 1 To 2
Integral = Application.WorksheetFunction.Sum((Cells(3 + i, 2) - Cells(2 + i, 2)) * (Cells(3 + i, 3) + Cells(2 + i, 3)) / 2)
Next i
Sheet1.Cells(4, 7) = Integral
End Sub
I believe the solution is simple, but at the moment, nothing comes to my mind!
I would appreciate it if someone showed me how to solve this!
Thank you in advance!

You dont have an accululative sum after each iteration of the loop
Sub Integral()
Dim i As Integer
Dim Integral As Double
Dim Sum_Area as Double
For i = 1 To 2
Integral = (Cells(3 + i, 2) - Cells(2 + i, 2)) * (Cells(3 + i, 3) + Cells(2 + i, 3)) / 2
Sum_Area = Sum_Area + Integral
Next i
Sheet1.Cells(4, 7) = Sum_Area
End Sub

Related

assign a result in a variable that i want to use later in the code vba

I did this code and i don't know how could i store the result (Sheets(x + 1).Cells(i, 5)), which is a column of numbers, in a variable that i want to use later in another function.
Maybe i should do a function and then add a sub to store the function.
Sub sumV40()
Dim i As Integer
Dim x
For x = 1 To Sheets.Count
For i = 1 To 10
Sheets(x + 1).Cells(i, 5) = Sheets(1).Cells(i, 1) + Sheets(x + 1).Cells(i, 1)
Next i
Next x
end sub()
So all you need to do is Dim a new Integer variable and put it on the left of an assignment operator (in this case for VBA it is the = sign). Then all you need to do is surround your entire algebraic calculation in parenthesis (although that is not necessary in this case). It looks like you're actively putting the calculated value in another cell so I broke that into a second step.
Example:
Dim i As Integer
Dim x
Dim total As Integer
For x = 1 To Sheets.Count
For i = 1 To 10
total = (Sheets(1).Cells(i, 1) + Sheets(x + 1).Cells(i, 1))
Sheets(x + 1).Cells(i, 5) = total
Next i
Next x

Excel Matrix Assignment by Referring to a Cell

I am trying to construct a 2x2 matrix dependent on values in some cells (say B1). The code shall take the reference and make some mathematical manipulations, then assign this value to a new cell.
Sub matrix2()
Dim matrix(1 To 2, 1 To 2) As String
k1 = Cells(1, 2).Value
For i = 1 To 2
For j = 1 To 2
k = (-1) ^ (i + j)
matrix(i, j) = "=B1*" & k
Next j
Next i
Range("D1:E2") = matrix
End Sub
In the end, I get what I want but I need to go to each cell and press Enter to convert them in a real value. What I should get here is a matrix dependent on the value in B1. When I change B1, the values in the matrix will automatically change.
Is there any way to make it happen more easily? Because, I will be dealing with 40x40 matrices in the end, and I don't want to go over 1600 cells and press Enter.
I doubt this is going to be helpfull right now, but maybe in the (near) future. With the new MAKEARRAY() function you could do this outside of VBA with relative ease:
Formula in D3:
=MAKEARRAY(2,2,LAMBDA(i,j,B1*(-1^(i+j))))
You have to use a variant-array - not a string-array
Try this:
Sub Matrix2()
Dim arr(1 To 2, 1 To 2) as Variant 'instead of String
k1 = Cells(1, 2).Value
For i = 1 To 2
For j = 1 To 2
k = (-1) ^ (i + j)
arr(i, j) = "=B1*" & k
Next
Next
ActiveSheet.Cells(8, 1).Resize(2, 2).Formula = arr
end sub

Find Distance between different coordinates

I have Location data (latitude and longitude) of 1000's of locations and need to compute the distance between each of them taken two combinations at a time.
Example:
Let's just say I have four location data (latitude and longitude data) and want to compute the distance between them
Location Latitude Longitude
1. New York(L1) 40.7128° N 74.0060° W
2. Paris(L2) 48.8566° N 2.3522° E
3. London(L3) 51.5074° N 0.1278° W
4. Moscow(L4) 55.7558° N 37.6173° E
Need to calculate the distance between possible combinations i.e distance between L1&L2, L1&L3, L1&L4, L2&L3, L2&L4 and L3&L4
Excel Formula I'm using to compute distance is
=ACOS(COS(RADIANS(90-Lat1)) *COS(RADIANS(90-Lat2)) +SIN(RADIANS(90-Lat1)) *SIN(RADIANS(90-Lat2)) *COS(RADIANS(Long1-Long2))) *6371
How can I calculate it for large data set say 100's or 1000's of locations?
Alternatively, you can create a VBA function and then loop through your table.
Add this code to a Module in the VBA editor:
Public Function DistBetweenCoord(Lat1 As Double, Long1 As Double, Lat2 As Double, Long2 As Double)
'Cell Formula
'ACOS(COS(RADIANS(90-Lat1)) *COS(RADIANS(90-Lat2)) +SIN(RADIANS(90-Lat1)) *SIN(RADIANS(90-Lat2)) *COS(RADIANS(Long1-Long2))) *6371
With WorksheetFunction
A = Cos(.Radians(90 - Lat1))
B = Cos(.Radians(90 - Lat2))
C = Sin(.Radians(90 - Lat1))
D = Sin(.Radians(90 - Lat2))
E = Cos(.Radians(Long1 - Long2))
DistBetweenCoord = .Acos(A * B + C * D * E) * 6371
End With
End Function
Now you can access this through code or in cell. Here is an example of in-cell:
=DistBetweenCoord(C1,D1,C2,D2)
Here is how to loop through all possible combinations in another Sub. Output is in immediate window.
Sub CalcAllDistances()
With Worksheets("Sheet1")
For i = 1 To 4
For j = i To 4
If i <> j Then
Debug.Print .Cells(i, 2) & " to " & .Cells(j, 2) & ": " & DistBetweenCoord(.Cells(i, 3), .Cells(i, 4), .Cells(j, 3), .Cells(j, 4))
End If
Next j
Next i
End With
End Sub
EDIT - To change output to Sheet2 try the following:
Sub CalcAllDistances()
Dim wks_Output As Worksheet
Set wks_Output = Worksheets("Sheet2")
Dim OutputRow As Long: OutputRow = 1
With Worksheets("Sheet1")
For i = 1 To 4
For j = i To 4
If i <> j Then
wks_Output.Cells(OutputRow, 1).Value = .Cells(i, 2) & " to " & .Cells(j, 2)
wks_Output.Cells(OutputRow, 2).Value = DistBetweenCoord(.Cells(i, 3), .Cells(i, 4), .Cells(j, 3), .Cells(j, 4))
OutputRow = OutputRow + 1
End If
Next j
Next i
End With
End Sub
I would use a matrix.
Create a sheet (like 'GeocodeList' or something) for the geocodes, like your city|lat|lon in the question. Then create a sheet (like 'Distances') for a matrix, where the column and row labels are the city names. Then you can parameter your excel formula using V.LOOKUPs that look up exact codes from GeocodeList.
The formula would look like this (X is row number, Y is column letter.):
=ACOS(COS(RADIANS(90-VLOOKUP($A(X); GEOCODETABLE, LATCOLINDEX, 0)))
*COS(RADIANS(90-VLOOKUP((Y)$1; GEOCODETABLE; LATCOLINDEX, 0)))
+SIN(RADIANS(90-VLOOKUP($A(X); GEOCODETABLE, LATCOLINDEX, 0)))
*SIN(RADIANS(90-VLOOKUP((Y)$1; GEOCODETABLE; LATCOLINDEX, 0)))
*COS(RADIANS(VLOOKUP($A(X); GEOCODETABLE, LATCOLINDEX, 0)-VLOOKUP((Y)$1; GEOCODETABLE; LONCOLINDEX, 0))))
*6371
So basically the VLOOKUP automatically fetches your parameters, and you can extend the formula for the whole matrix.

Excel formula to find the X nearest combination of values to a certain value combination

In Excel, we have 3 columns with values in them Length, Width, and Height of objects. Each row stands for 1 object, now we need to find the X number of objects that fit the most together.
For Example:
Now let's say we need the 2 closest sets of values, the output should give Nbr. 1 and 2 because [abs(11-10) + abs(9-8) + abs(4-5)] is the smallest value you'll get. Here we needed to find the 2 closest but sometimes we need to find the 25 closest sets of values.
Moreover, some might find Height not important or really important so you may want to lower or heighten its importance by adding in factors F(1,2,3) with which you multiply a part of the formula:
[F1 * abs(11-10) + F2 * abs(9-8) + F3 * abs(4-5)]
I tried to find the first (second, third and so on) smallest difference in value which works for just one variable but not multiple ones at the same time with:
=INDEX(A$2:A$5002,MATCH(SMALL(ABS(B$2:B$5002-B2),2),ABS(B$2:B$5002-B2),0))
I don´t know an Excel formula to solve this problem as I want to find the X nearest combination of values.
I expect a result showing the row numbers of X objects that fit the best together.
I Created a VBA Excel code that seems to work pretty nice in finding out which value combinations fit best together. It shows the closest values and the sum of all differences to determine the combination that works best. I did remove the first row of the picture in the description though. If anyone can improve, please do.
Sub test()
Dim last_row As Long
last_row = Cells(Rows.Count, 1).End(xlUp).Row
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim m As Integer
Dim L As Integer
Dim W As Integer
Dim H As Integer
Dim AantalGelijken As Integer
Dim FL As Integer
Dim FW As Integer
Dim FH As Integer
FL = 1
FW = 1
FH = 0.8
AantalGelijken = InputBox("How many comparable sets do you need", "Number")
L = 2
W = 3
H = 4
For i = 1 To last_row
For j = 1 To last_row
If i <> j Then
Cells(j, 5).Value = FL * Abs(Cells(i, L) - Cells(j, L)) + FW * Abs(Cells(i, W) - Cells(j, W)) + FH * Abs(Cells(i, H) - Cells(j, H))
End If
Next j
For k = 1 To AantalGelijken
Cells(i, 5 + k) = WorksheetFunction.Index(Range("A1:A9999"), WorksheetFunction.Match(WorksheetFunction.Small(Range("E1:E9999"), k), Range("E1:E9999"), 0))
Cells(i, AantalGelijken + 6) = Cells(i, AantalGelijken + 6) + WorksheetFunction.Small(Range("E1:E9999"), k)
Next k
Range("E1:E9999").Clear
Next i
End Sub
`

VBA Application-defined or object-defined error

I am working with VBA for Excel.
I get the "Application defined or object defined" error each time I run this code.
Here it is:
Sub Test()
Dim i As Integer, j As Integer, k As Integer, l As Integer, t As Integer
Dim row As Integer
Dim Maturite As Integer
Dim tsup As Double, tinf As Double
Dim datetaux As Date, datejouissance As Date
Dim taux As Double
For i = 2 To 770
Maturite = Sheets("Em").Cells(i, 19)
datejouissance = Sheets("Em").Cells(i, 14)
For l = 2 To 255
For k = 0 To 10
For t = 1 To 10
row = 13 * k + 2
datetaux = Sheets("TSR").Cells(row, l)
taux = Sheets("TSR").Cells(13 * k + 3, l)
If taux <> 0 Then
If datejouissance = datetaux Then
If 91 <= Maturite And Maturite <= 182 Then
tsup = Sheets("TSR").Cells(row + 2, j)
tinf = Sheets("TSR").Cells(row + 1, j)
Sheets("Em").Cells(i, 21).Value = ((tsup - tinf) * (Maturite - 91) / (182 - 91)) + tinf
End If
End If
End If
Next
Next
Next
Next
End Sub
I get the error at :
tsup = Sheets("TSR").Cells(row + 2, j)
I tried using :
tsup = Sheets("TSR").Cells(row + 2, j).Value
The type of Sheets("TSR").Cells(row + 2, j).Value is Double.
But it's not working. I can't seem to understand what the problem is.
Thanks in advance
I think you may need to check the value of j. As far as I can see from your code its value remains 0. Column 0 does not exist and will lead to the given error.
You address the cell using the integer j, but you don't assign a value to j.
Thus, VBA fills it with the standart value for integers: 0, directing your call to Sheets("TSR").Cells(row + 2, 0) and producing an error.

Resources