无法在Excel VBA上创build循环并打印结果

我是Excel VBA的新手,我想计算两个primefaces之间的距离,并为所有想要的情况计算一个循环

与Excel中的坐标B(i),C(i),D(i)对应x,y,z直angular坐标。

这些primefaces位于:一排(i)和另一排(i + 5)

我写这个algorithm,但我不能转移到Excel VBA

For i=4 to 1000 For j=9 to 1000 d=SQRT(POWER(B(i)-B(j),2)+ POWER(C(i)-C(j),2)+ POWER(D(i)-D(j),2)) print **d** in (P(i)) #want to print the distance **d** in a case j=j+4 # **j** is a multiple of 4 i=i+4 # **i** is a multiple of 4 next i 

谢谢,这是我的第一个问题

我认为以下几点应该适合你:

 Sub FindDistances() Dim i As Long, j As Long Dim r As Long, c As Long 'row and column indices for output Dim data As Variant Application.ScreenUpdating = False 'useful when doing a lot of writing data = Range("B4:D1000").Value 'data is a 1-based array c = 5 'column E For i = 1 To UBound(data) - 5 Step 4 r = 1 'first row printed in -- adjust if need be For j = i + 5 To UBound(data) Step 4 Cells(r, c).Value = Sqr((data(i, 1) - data(j, 1)) ^ 2 + (data(i, 2) - data(j, 2)) ^ 2 + (data(i, 3) - data(j, 3)) ^ 2) r = r + 1 Next j c = c + 1 Next i Application.ScreenUpdating = True End Sub 

像这样的东西? 在VBA中,您指的是单元Cells(row, column)单元Cells(row, column) 。 数据应该位于名为Sheet1的工作表Sheet1 。 我正在计算每个维度分开( d1, d2, d3 )只是为了阅读简单。 如果你喜欢,你可以合并这四行。 编辑:读你上面的意见,我添加一个嵌套循环(j)。

 Sub Distances() Dim i As Integer Dim j As Integer Dim d1 As Double, d2 As Double, d3 As Double, d As Double For i = 4 To 1000 Step 4 'Can't understand your data, but Step 4 tries to account for your j=j+4 and i=i+4 For j = 9 To 1000 Step 4 d1 = (Worksheets("Sheet1").Cells(i, 2) - Worksheets("Sheet1").Cells(j, 2)) ^ 2 d2 = (Worksheets("Sheet1").Cells(i, 3) - Worksheets("Sheet1").Cells(j, 3)) ^ 2 d3 = (Worksheets("Sheet1").Cells(i, 4) - Worksheets("Sheet1").Cells(j, 4)) ^ 2 d = Sqr(d1 + d2 + d3) Worksheets("Sheet1").Cells(i, 16).Value = d Next j Next i End Sub 
 Option Explicit Sub AtomDistance() ' ' AtomDistance Macro1 ' ' Dim i As Integer Dim j As Integer Dim Distance As Double Dim Column As String Column = InputBox("Which column you want to print results(put a letter)?") Dim MyCell11 As String Dim MyCell12 As String Dim MyCell13 As String Dim MyCell21 As String Dim MyCell22 As String Dim MyCell23 As String Dim MyCell3 As String j = 9 For i = 4 To 12 MyCell3 = Column & i MyCell11 = "B" & i MyCell12 = "C" & i MyCell13 = "D" & i MyCell21 = "B" & j MyCell22 = "C" & j MyCell23 = "D" & j Distance = (((Range(MyCell11).Value - Range(MyCell21).Value) ^ 2) + ((Range(MyCell12).Value - Range(MyCell22).Value) ^ 2) + ((Range(MyCell13).Value - Range(MyCell23).Value) ^ 2)) ^ 0.5 If i Mod 4 = 0 Or j Mod 4 = 0 Then Range(MyCell3).Value = Distance End If j = j + 1 Next i