【发布时间】:2014-08-07 21:10:09
【问题描述】:
那么问题来了:
我需要插入输入到模板的值。听起来很容易,对吧?问题是,这些值并不总是按数字顺序排列,所以它弄乱了我的插值函数。我的插值函数输入 x 值(在本例中为 HP,这是需要以数字方式排序的参数,而不会弄乱与之相关的数据)、y 值(您要在 ?HP 处找到的参数)和x_value 您想在其中找到 y 参数。一些 y 参数是方程,所以我想不出一种方法来完全重新排序列而不弄乱数据。我认为应该有一种方法可以参考集合中 HP 的等级,选择相关的 y 值,并使用这些值进行插值。话虽如此,我似乎无法弄清楚该怎么做。我已经在一些代码上工作了很长一段时间。我以前从未真正使用过 VBA,所以它一直在为我的钱奔波。我到目前为止的代码如下:
Function organize(ByVal x As Object)
' Declarations for finding Ranks
Dim Array_Size As Integer
Array_Size = Application.WorksheetFunction.Count(x.cells) + Application.WorksheetFunction.CountBlank(x.cells)
Dim Ranks As Variant
ReDim Ranks(1 To Array_Size)
Dim j As Integer 'initiate counter
For j = 1 To Array_Size
If x.cells(j).Value <> 0 Then
Ranks(j) = Application.WorksheetFunction.Rank_Eq(x.cells(i).Value, x.cells, 1) 'assign rank to i'th position in array
End If
Next j
organize = Ranks()
End Function
Function lin_2xy(ByVal x1 As Single, ByVal y1 As Single, _
ByVal x2 As Single, ByVal y2 As Single, _
ByVal x_value As Single)
If x1 = x2 Then
lin_2xy = [#N/A]
Else
lin_2xy = y1 + (y2 - y1) / (x2 - x1) * (x_value - x1)
End If
End Function
Function Sort_Then_Interpolate(ByVal x As Object, ByVal y As Object, ByVal x_value As Single)
'Declarations for interpolating
Dim i As Integer ' counter.
Dim Current_x As Single ' x value
Dim Next_x As Single ' next higher x value
Dim Current_y As Single ' y value
Dim Next_y As Single ' next higher y value
Dim LFound As Boolean ' = true if found.
Dim matrix() As Variant
matrix = organize(x.cells)
LFound = False
For i = 1 To UBound(matrix)
match_value = Application.WorksheetFunction.Match(i, matrix, 0)
next_match = Application.WorksheetFunction.Match(i + 1, matrix, 0)
Current_x = x.cells(match_value).Value
Next_x = x.cells(next_match).Value
Current_y = y.cells(match_value).Value
Next_y = y.cells(next_match).Value
If ((Current_x - x_value) * (Next_x - x_value) <= 0#) Then
Sort_Then_Interpolate = lin_2xy(Current_x, Current_y, Next_x, Next_y, x_value)
LFound = True
End If
Next i
If (LFound = False) Then Sort_Then_Interpolate = [#N/A]
End Function
【问题讨论】:
-
无需深入研究您的代码,根据您的描述,Collection 或 Dictionary 都可能对您有所帮助。我也很想建议使用类,但如果你刚刚开始,这些是非常先进的。无论如何,您能否发布一个链接,该链接可能指向您的源数据的屏幕截图和您想要的输出?如果不是我,有人会从链接中为您编辑屏幕截图。通过这种方式,我们可以了解您想要做得更好。