如何从“总货币” VBA / BDP中提取货币

时间:2018-10-24 08:22:05

标签: excel vba excel-vba bloomberg

我有一个列表:

           Price in EUR       Price in Home Country
Total AUD
Svenska     10
Ubinse      15 
Illuao      20
Total USD
Zelo        12
Jhasma      11
Hedsaw      17

理想情况下,我想使用VBA插入一个子项,该子项在Price in Home Country列的每一行中插入BDP函数

类似:

for i = 1 to 7
if IsEmpty(Cells(i,2)) = True Then
Else
Cells(i,3).Value = PriceHomeCountry(Cells(i,2), Cells(ws.Rows.Count,2).End(xlBottom).Offset(1,-1)
End if 
Next i 

请注意,我想使用Cells(ws.Rows.Count,2).End(xlBottom).Offset(1,-1).Value来引用上面的“总计Insert Currency

我不确定如何构造PriceHomeCountry()函数

建议:

Function PriceHomeCountry(rng1 as Range, rng2 as Range)
'I want to basically separate the "Total" from the "Currency" in rng2,let's call the result rng2.1
PriceHomeCountry = "=BDP( "EUR" & rng2.1 & " Crncy")*rng1
End Function

1 个答案:

答案 0 :(得分:3)

此代码应该可以解决问题。我无法使用BDP公式进行测试,因为我没有加载项,因此我给出了三种使用方式。

Sub Test()

    Dim rCell As Range
    Dim CalcRange As Range
    Dim CountryRange As Range
    Dim TotalCell As Range
    Dim HomeCountry As String

    'Every reference to a range that starts "." will be referencing Sheet1.
    With ThisWorkbook.Worksheets("Sheet1")

        'Define the ranges we're working with.
        Set CountryRange = .Range("A2:A9")
        Set CalcRange = .Range("C2:C9")

        'Look at each cell in C2:C9.
        For Each rCell In CalcRange
            If Not IsEmpty(rCell.Offset(, -1)) Then
                'Find the first cell before the current rCell in column A that contains the word Total.
                Set TotalCell = CountryRange.Find(What:="Total", After:=rCell.Offset(, -2), _
                    LookIn:=xlValues, LookAt:=xlPart, SearchDirection:=xlPrevious)

                'If found then check the found value is in a row higher than rCell.
                ' - FIND wraps when it reaches the top so could find a Total from lower down.
                If Not TotalCell Is Nothing Then
                    If TotalCell.Row < rCell.Row Then
                        rCell = PriceHomeCountry(rCell.Offset(, -1), TotalCell)

                        'If PriceHomeCountry isn't working this will place the formula in column C.
                        'rCell.Formula = "=BDP(""EUR" & Split(TotalCell, " ")(1) & " Curncy"",""PX_LAST"")"
                    End If                        
                End If
            End If
        Next rCell
    End With

End Sub

Public Function PriceHomeCountry(rng1 As Range, rng2 As Range) As Variant

    'Should work if you set a reference to the Bloomberge add-in in Tools ~ References.
    PriceHomeCountry = BDP("EUR" & Split(rng2, " ")(1), " Curncy", "PX_Last") * rng1

    'Might work without setting a reference.
    'PriceHomeCountry = Application.Run("BDP", "EUR" & Split(rng2, " ")(1), " Curncy", "PX_Last") * rng1

End Function  

编辑:同时还要感谢@assylias对公式构造的注意。