[英]VBA Excel - How can I automatically fill a series in excel, based on the value of another cell?
I have two columns in excel spreadsheet. 我在Excel电子表格中有两列。 'Distance' and 'Bearing'.
“距离”和“轴承”。 As shown in the below image the first distance value is 58.23 and the bearing value for the first distance is -43.45 as shown in image 1.
如下图所示,第一距离值为58.23 ,第一距离的方位值为-43.45 ,如图1所示。
I want to divide the distance into a meter each, as in 1,2,3,4...58 (so that 58 meters is broken into 58 equal parts) in one column (Distance1) and fill the next column with value -43.45 (Bearing1) from 1 to 58 as shown in image 2. I want to generate this in a new sheet. 我想将距离分别划分为一米,例如在一列(Distance1)中将1,2,3,4 ... 58(这样一来,58米被分成58个相等的部分),并用值填充下一列-从1到58的43.45(Bearing1),如图2所示。我想在新表中生成它。
After the first row, the code should go to the next distance row (ie, 20.70) and repeat step 1, but should add it to the previous 1 to 58 cells. 在第一行之后,代码应转到下一个距离行(即20.70)并重复步骤1,但应将其添加到前1到58个单元格中。 ie 58, 59, 60 and fill the bearing1 column value with -42.48 and so on.
例如58、59、60,并用-42.48填充bearing1列的值,依此类推。 As shown in Image 3.
如图3所示。
I am new to VBA and will be really helpful if someone can help me out :) 我是VBA的新手,如果有人可以帮助我,将会非常有帮助:)
A couple of row counters and Single type variables and a few Loops will do. 几个行计数器和单个类型变量以及几个循环就可以了。
As you are new to VBA, will not consider performance optimization here. 由于您是VBA的新手,因此这里将不考虑性能优化。 Hope below untested code will get you love doing VBA programming.
希望下面未经测试的代码能使您喜欢进行VBA编程。 Code should self-explain the purpose.
代码应该自我解释的目的。 Ask if don't understand.
询问是否不明白。
Here assuming Data is on columns A and B as per screenshot. 在这里,假设数据按照截图在A和B列上。 And the output data will be from D2 and E2 downwards.
并且输出数据将从D2和E2向下。
Option Explicit
Sub FillDistanceBearing()
Dim lRowOutput As Long ' Row to start storing data
Dim lDistance As Long ' Incremental Distance
Dim lLoop1 As Long, lLoop2 As Long ' Row counters for Loops
Dim gDistance As Single, gBearing As Single ' Variables to store the points
lRowOutput = 2 ' Row to start storing the series at some column
lDistance = 0 ' Start from zero
' #1 - Loop the main data
lLoop1 = 2 ' For A2
Do Until IsEmpty(Range(lLoop1, "A"))
' Store the Distance|Bearing values into variables
gDistance = Range(lLoop1, "A").Value
gBearing = Range(lLoop1, "B").Value
' #2 - Loop the distance from 1 to the integer value of the distance
For lLoop2 = 1 To Int(gDistance)
lDistance = lDistance + 1 ' Increment distance
' Store the values in Columns D and E for Distance1, Bearing1
Range(lRowOutput, "D").Value = lDistance
Range(lRowOutput, "E").Value = gBearing
lRowOutput = lRowOutput + 1 ' Move to next row for storing output
Next
lLoop1 = lLoop1 + 1 ' Move to next data row
Loop
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.