我有一个Excel表,其中以股市符号作为列标题,例如HES,MTDR,OXY等。这些列包含与相应标题关联的市场数据:
类型HES MTDR OXY ...
打开62.22 30.56 78.52 ...
关闭62.96 30.52 79.01 ...
...
当我收到特定的股票代号时,例如OXY,来自
Public function getMarketData(colName as String, dataType as Integer) as Double
我需要在该股票代码开头的列中访问所需数据,例如
getMarketData = [tblMarketData[OXY]].Rows(dataType)
问:如何从colName中提取OXY以用于上述语句?我需要使用EVALUATE吗?
getMarketData = [tblMarketData[colName]].Rows(dataType)
生成错误消息'Object required',因为tblMarketData []期望实际的列标题为OXY,而不是包含OXY的变量。
答案 0 :(得分:0)
一种方法是使用标头作为键来访问ListColumns
对象。然后,您可以使用DataBodyRange
属性读取该列中包含的数据。在下面的示例中,我已将该范围读入数组,并将该项目传递回了索引6。
Private Function FetchData(colName As String)
Dim tbl As ListObject
Dim col As ListColumn
Dim data As Variant
Set tbl = Sheet1.ListObjects("Table1")
Set col = tbl.ListColumns(colName)
data = col.DataBodyRange.Value2
'Obtain 6th item in array.
FetchData = data(6, 1)
End Function
该函数可以这样调用:
Debug.Print FetchData("OXY")
编辑后续问题:
列名称的提取将在很大程度上取决于完整搜索字符串的性质。但是,原则上,您将迭代每个列标题,以查看是否可以找到某种匹配项。在下面的示例中,我进行了一个简单的Like
比较,例如,如果文本在其他地方包含“ HES”,肯定会失败。无法看到您的文本字符串,很难更精确,因此您可能必须根据所拥有的文本字符串来严格提取规则。
该函数可能如下所示:
Private Function FetchDataItem(txt As String, idx As Long) As Variant
Dim tbl As ListObject
Dim col As ListColumn, refCol As ListColumn
Dim data As Variant
'Find the appropriate column.
Set tbl = Sheet1.ListObjects("Table1")
For Each col In tbl.ListColumns
If txt Like "*" & col.Name & "*" Then
Set refCol = col
Exit For
End If
Next
'If there's no match then return empty.
If refCol Is Nothing Then Exit Function
'Retrieve the data item from array.
data = refCol.DataBodyRange.Value2
'If index is out of range then return empty.
If idx < LBound(data, 1) Or idx > UBound(data, 1) Then Exit Function
FetchDataItem = data(idx, 1)
End Function
...,可以如下调用(包括几个示例字符串):
Public Sub RunMe()
Dim arbitraryText As String, failText As String
Dim col As ListColumn
arbitraryText = "randomtextwithOXYinit"
'Read item 6 from column OXY.
Debug.Print FetchDataItem(arbitraryText, 6)
'An example of how the extraction could fail - note the 'HES' in the string.
failText = "I'M A THESBIAN BUT AM LOOKING FOR OXY"
Debug.Print FetchDataItem(failText, 6)
End Sub