VBA Bloomberg API - excel

I want to run a macro that brings me the following value INTERVAL_PERCENT_CHANGE from:
The ticher of the fund concerned S3.Range(Cells(3, 76), Cells(3, 77)).
Start and end dates S3.Cells(i, 73).Value and S3.Cells(i, 74).Value
Currency S3.Cells(2, 76).Value
from the Bloomberg APIs. But I get a soft error message
"invalid procedure call or argument".
I really tried everything but there is something that escapes me.
the underlined line is the following:
range(cells(4,76),cells(12,77)).value msg.GetElement("securitydata").GetValue(0).GetElement("fieldData").GetElement("INTERVAL_PERCENT_CHANGE").Value
Thank you for all your answers and insights. below the code in full
Sub ref_data()
Dim session As blpapicomLib2.session
Set session = New session
session.Start
Dim Service As blpapicomLib2.Service
session.OpenService ("//blp/refdata")
Set Service = session.GetService("//blp/refdata")
Dim Request As blpapicomLib2.Request
Set Request = Service.CreateRequest("ReferenceDataRequest")
Request.Append "securities", "S3.Range(Cells(3, 76), Cells(3, 77)).Value"
Request.Append "fields", "INTERVAL_PERCENT_CHANGE"
Dim overrides As Element
Set overrides = Request.GetElement("overrides")
Dim override As Element
Set override = overrides.AppendElment
Dim i As Integer
For i = 4 To 12
Dim override1 As Element
Set override1 = overrides.AppendElment
override1.SetElement "fieldId", "Start_Date_Override"
override1.SetElement "value", "S3.Cells(i, 73).Value" 'Replace date with the cell reference eg Range("B10").Value
Dim override2 As Element
Set override2 = overrides.AppendElment
override2.SetElement "fieldId", "End_Date_Override"
override2.SetElement "value", "S3.Cells(i, 74).Value" 'Replace date with the cell reference eg Range("A10").Value
Dim override3 As Element
Set override3 = overrides.AppendElment
override3.SetElement "fieldId", "CRNCY"
override3.SetElement "value", "S3.Cells(2, 76).Value" 'Replace EUR with the cell reference eg Range("A10").Value
session.SendRequest Request
Dim blpevent As blpapicomLib2.Event
Dim it As blpapicomLib2.MessageIterator
Dim msg As blpapicomLib2.Message
Dim finalResponse As Boolean
Do While finalResponse = False
Set blpevent = session.NextEvent
Set it = blpevent.CreateMessageIterator
Do While it.Next
Set msg = it.Message
If blpevent.EventType = RESPONSE Or blpevent.EventType = PARTIAL_RESPONSE Then
range(cells(4,76),cells(12,77)).value msg.GetElement("securitydata").GetValue(0).GetElement("fieldData").GetElement("INTERVAL_PERCENT_CHANGE").Value
End If
If blpevent.EventType = RESPONSE Then
finalResponse = True
End If
Loop
Loop
Next i
End Sub

Related

excel hyperlink function to variable

I have a lot of cells with hyperlink function. One example: A1=HYPERLINK("T:\projekt1\61VWAus.xlsx";"61VWAus.xlsx" ). I need go through each cell and check each hyperlink if it is valid file. How can I get the hyperlink "T:\projekt1\61VWAus.xlsx" to a variable from the formula value? Do I have to use string operation to get it or is there any direct function to get only hyperlink?
Thanks
I have found the solution:
Function check_hyperlink(rng As Range) As Boolean
Dim oFSO As Object
Dim str_Hyperlink As String
Dim exists As Boolean
Dim str_form As String
Dim arr_str_form As Variant
Set oFSO = CreateObject("Scripting.FileSystemObject")
str_form = rng.Cells(1, 1).Formula
If Left(str_form, 10) = "=HYPERLINK" Then
arr_str_form = Split(str_form, Chr(34))
str_Hyperlink = arr_str_form(1)
exists = oFSO.FileExists(str_Hyperlink)
If exists Then
check_hyperlink = True
Else
check_hyperlink = False
End If
Else
check_hyperlink = False
End If
End Function

OPC DA Client - Unable to assign item.Value to VBA variable

Below is an OPC Client written in VBA. It is using the OPC Foundation DA libraries. I am able to get the current value of the item (I can read it in locals window), but it is not assigning the value to myValue = theItem.Value Hovering over theItem.Value during a break shows the value as well.
Any thoughts?
Public Sub ReadValue()
Dim serverNames As Variant
Dim listServers As Variant
Dim i As Integer
Dim theStates As Variant
Set theServer = New OPCServer
serverNames = theServer.GetOPCServers
theStates = Array("Disconnected", "Running", "Failed", "No Configuration", "Suspended", "In Test")
For i = LBound(serverNames) To UBound(serverNames)
Debug.Print (serverNames(i))
Next i
theServer.Connect ("MyOPCServer")
Debug.Print theServer.VendorInfo
Debug.Print theServer.MajorVersion & "." & theServer.MinorVersion
Debug.Print theStates(theServer.ServerState)
Debug.Print theServer.StartTime
Debug.Print theServer.CurrentTime
Debug.Print theServer.LastUpdateTime
'Groups
Dim theGroup As OPCGroup
Dim theGroups As OPCGroups
If theGroups Is Nothing Then
Set theGroups = theServer.OPCGroups
End If
If theGroup Is Nothing Then
Set theGroup = theGroups.Add("testing")
txtName = theGroup.name
End If
theGroup.UpdateRate = CLng(1000)
theGroup.DeadBand = CLng(1)
theGroup.TimeBias = CLng(0)
theGroup.IsActive = CBool(1)
theGroup.IsSubscribed = CBool(1)
'
Dim theItem As OPCItem
Dim theItem1 As OPCItem
Dim myItems As Variant
Dim myValue As Variant
Dim myWriteValues As Variant
Dim handles(1) As Long
Dim Errors() As Long
Dim CancelID As Long
Dim TransID As Long
myItems = Array("MyPathBlahBlahBlah.CV")
myWriteValues = Array(8, 0, 1)
For i = LBound(myItems) To UBound(myItems)
Set theItem = theGroup.OPCItems.AddItem(myItems(i), currentHandle)
myValue = theItem.Value
handles(1) = theGroup.OPCItems.Item(1).ServerHandle
theGroup.OPCItems.Remove 1, handles, Errors
Next i
theServer.Disconnect
End Sub
After review/trouble shooting.
The OPCItem object provides methods to read the current value of the item in the server and write a new value to the item. I have included these facilities into this dialog. The read method provided on an OPCItem object performs a synchronous read from the server and can be configured to read either from cache or from the device. To read from cache both the group and item should be active, but synchronous read operations directly from the device do not depend on the active state of either the group or item.
Adding the following code allowed me to assign to variable.
Dim source As OPCDataSource
Dim myValue As Variant
source = OPCDevice
theItem.Read source, myValue

Run-time error '-2147467261 (80004003) Object reference not set to an instance of an object

I'm getting the following error on the line 'ua' below. I'm trying to automate an Upsert to Salesforce through VBA using the enabler4excel object [automationObject].
Run-time error '-2147467261 (80004003)
Object reference not set to an instance of an object
Here is my code:
Dim addin As Office.COMAddIn
Dim automationObject As Object
For Each addin In Application.COMAddIns
If addin.Description = "Enabler for Excel" Then
Set automationObject = addin.Object
End If
Next addin
Dim error
result = automationObject.LogIn(Username,Password,"https://test.salesforce.com", error)
If result = False Then
MsgBox error
End
End If
Range("b1").Select
Selection.End(xlDown).Select
bot_acc = ActiveCell.Row
Dim ExternalId As String
ExternalId = Range("A1")
Dim ObjectName As String
ObjectName = "Account"
Dim AccUpArray(13, 9999) As Variant
For Column = 0 To 12
For Row = 0 To bot_acc - 2
AccUpArray(Column, Row) = Worksheets("Account").Range("A2").Offset(Row, Column)
Next Row
Next Column
ua = automationObject.UpsertData(AccUpArray, ObjectName, ExternalId, False, Nothing, error)
If Not error = Empty Then
MsgBox error
End
End If
I don't see where you dim ua but it is an object I assume (i.e. not an integer or string or boolean...) which means you need to use the keyword set
Set ua = automationObject.UpsertData(AccUpArray, ObjectName, ExternalId, False, Nothing, error)
Not seeing where you dim this could also mean you are not using Option Explicit. You should be.

Application-defined or object-defined error in Excel VBA

I'm getting said error in using VBA in Excel on the following code:
Private Sub XMLGen(mapRangeA, mapRangeB, ticketSize, mapping)
Dim fieldOneArr As Variant
Dim fieldTwoArr As Variant
Dim row As Long
Dim column As Long
Dim infoCol As Long
Dim endInfo As Long
Dim objDom As DOMDocument
Dim objNode As IXMLDOMNode
Dim objXMLRootelement As IXMLDOMElement
Dim objXMLelement As IXMLDOMElement
Dim objXMLattr As IXMLDOMAttribute
Set ws = Worksheets("StockData")
Dim wsName As String
Set objDom = New DOMDocument
If ticketSize = 8 Then
wsName = "A7Tickets"
ElseIf ticketSize = 16 Then
wsName = "A8Tickets"
Else
wsName = "A5Tickets"
End If
Set ps = Worksheets(wsName)
'create processing instruction
Set objNode = objDom.createProcessingInstruction("xml", "version='1.0' encoding='UTF-8'")
objDom.appendChild objNode
'create root element
Set objXMLRootelement = objDom.createElement("fields")
objDom.appendChild objXMLRootelement
'create Attribute to the Field Element and set value
Set objXMLattr = objDom.createAttribute("xmlns:xfdf")
objXMLattr.NodeValue = "http://ns.adobe.com/xfdf-transition/"
objXMLRootelement.setAttributeNode objXMLattr
infoCol = 1
fieldOneArr = Worksheets(mapping).range(mapRangeA)
fieldTwoArr = Worksheets(mapping).range(mapRangeB)
For row = 1 To UBound(fieldOneArr, 1)
For column = 1 To UBound(fieldOneArr, 2)
'create Heading element
Set objXMLelement = objDom.createElement(fieldOneArr(row, column))
objXMLRootelement.appendChild objXMLelement
'create Attribute to the Heading Element and set value
Set objXMLattr = objDom.createAttribute("xfdf:original")
objXMLattr.NodeValue = (fieldTwoArr(row, column))
objXMLelement.setAttributeNode objXMLattr
objXMLelement.Text = ps.Cells(row, infoCol)
infoCol = infoCol + 1
endInfo = endInfo + 1
If endInfo = 4 Then
infoCol = 1
End If
Next column
Next row
'save XML data to a file
If ticketSize = 2 Then
objDom.Save ("C:\ExportTestA5.xml")
MsgBox "A5 XML created"
ElseIf ticketSize = 8 Then
objDom.Save ("C:\ExportTestA7.xml")
MsgBox "A7 XML created"
Else
objDom.Save ("C:\ExportTestA8.xml")
MsgBox "A8 XML created"
End If
End Sub
When I hit debug it points to this line:
fieldOneArr = Worksheets(mapping).range(mapRangeA)
I know that .Range is supposed to be upper case but it keeps on setting it to lower case automatically whenever I correct it.
This code is meant to create an XML file and then write the details from the chosen worksheet (based on the ticketSize variable) into the correct XML fields. Hence I have a mapping worksheet from which I write the field and attribute names, and then write in the info from the correct ticket size worksheet into the text property of the element.
You should define the types of your function parameters, in this case mapRangeA As String. Office object methods and properties are often not very helpful with their error messages, so it's better to have a type mismatch error if you have a problem with a parameter.

VBA code running horrendously slow

I have a loop that can go on for ages, although the "Enheder" worksheet only has like 10 rows, and the dataset im loadin has maybe 300 rows, it's taking a REALLY long time when I try to import.
Public Function ImportData()
Dim resultWorkbook As Workbook
Dim curWorkbook As Workbook
Dim importsheet As Worksheet
Dim debugsheet As Worksheet
Dim spgsheet As Worksheet
Dim totalposts As Integer
Dim year As String
Dim month As String
Dim week As String
Dim Hospital As String
Dim varType As String
Dim numrows As Integer
Dim Rng As Range
Dim colavg As String
Dim timer As String
Dim varKey As String
year = ImportWindow.ddYear.value
month = ImportWindow.ddMonth.value
week = "1"
varType = ImportWindow.ddType.value
Hospital = ImportWindow.txtHospital.value
Set debugsheet = ActiveWorkbook.Sheets("Data")
Set spgsheet = ActiveWorkbook.Sheets("Spørgsmål")
Set depsheet = ActiveWorkbook.Sheets("Enheder")
Set resultWorkbook = OpenWorkbook()
setResultColVars debugsheet
'set sheets
Set importsheet = resultWorkbook.Sheets("Dataset")
numrows = debugsheet.UsedRange.Rows.Count
'make sure that the enhed can be found in the importsheet, so the units can be extracted accordingly
If Not (importsheet.UsedRange.Find("afdeling") Is Nothing) Then
Dim DepColumn
Dim aCell
DepColumn = importsheet.UsedRange.Find("afdeling").column
'sort importsheet to allow meaningfull row calculations
Set aCell = importsheet.UsedRange.Columns(DepColumn)
importsheet.UsedRange.Sort Key1:=aCell, Order1:=xlAscending, Header:=xlYes
Dim tempRange As Range
Dim SecColumn
Dim secRange As Range
'find row ranges for departments
Application.ScreenUpdating = False
'**Here's the loop that will go on for aaaaaages until I decide to ctrl+pause**
For Each c In depsheet.UsedRange.Columns(1).Cells
splStr = Split(c.value, "_")
If UBound(splStr) = -1 Then
ElseIf UBound(splStr) = 0 Then
totalposts = totalposts + IterateColumns(GetRowRange(importsheet, DepColumn, splStr(0)), spgsheet, importsheet, debugsheet, year, month, week, Hospital, splStr(0), 0, varType, False)
ElseIf UBound(splStr) = 1 And Not (importsheet.UsedRange.Find("afdeling_" & splStr(0)) Is Nothing) Then
totalposts = totalposts + IterateColumns(GetRowRange(importsheet, importsheet.UsedRange.Find("afdeling_" & splStr(0)).column, splStr(1)), spgsheet, importsheet, debugsheet, year, month, week, Hospital, splStr(0), splStr(1), varType, False)
End If
Next
Application.ScreenUpdating = True
' go through columns to get total scores
totalposts = totalposts + IterateColumns(importsheet.UsedRange, spgsheet, importsheet, debugsheet, year, month, week, Hospital, 0, 0, varType, True)
resultWorkbook.Close Saved = True
ResultsWindow.lblPoster.Caption = totalposts
ImportWindow.Hide
ResultsWindow.Show
Else
MsgBox "Kunne ikke finde afdelingskolonnen. Kontroller at der er er en kolonne med navnet 'afdeling' i dit datasæt"
End If
End Function
Function GetRowRange(sheetRange, column, value) As Range
'check for a valid section column
sheetRange.AutoFilterMode = False
sheetRange.UsedRange.AutoFilter Field:=column, Criteria1:=value
Set GetRowRange = sheetRange.UsedRange.SpecialCells(xlCellTypeVisible)
sheetRange.AutoFilterMode = False
End Function
'iterates through columns of a range to get the averages based on the column headers
Function IterateColumns(varRange As Range, spgsheet, importsheet, resultsheet, year, month, week, Hospital, dep, sec, varType, sortspg As Boolean)
Dim numrows
Dim totalposts
Dim usedRng
totalposts = 0
numrows = resultsheet.UsedRange.Rows.Count
Dim insert
insert = True
If Not (varRange Is Nothing) Then
' go through columns to get scores
For i = 1 To varRange.Columns.Count
Dim tempi
tempi = numrows + totalposts + 1
Set Rng = varRange.Columns(i)
With Application.WorksheetFunction
'make sure that the values can calculate
If (.CountIf(Rng, "<3") > 0) Then
colavg = .SumIf(Rng, "<3") / .CountIf(Rng, "<3")
insert = True
Else
insert = False
End If
End With
'key is the variable
varKey = importsheet.Cells(1, i)
'only add datarow if the data matches a spg, and the datarow is not actually a department
If (sortSpgs(varKey, spgsheet, sortspg)) And (insert) And Not (InStr(key, "afdeling")) Then
resultsheet.Cells(tempi, WyearCol).value = year
resultsheet.Cells(tempi, WmonthCol).value = month
resultsheet.Cells(tempi, WweekCol).value = "1"
resultsheet.Cells(tempi, WhospCol).value = "Newport Hospital"
resultsheet.Cells(tempi, WdepCol).value = "=VLOOKUP(N" & tempi & ",Enheder!$A:$B,2,0)"
resultsheet.Cells(tempi, WsecCol).value = "=IFERROR(VLOOKUP(O" & tempi & ",Enheder!$A:$B,2,0),"" "")"
resultsheet.Cells(tempi, WdepnrCol).value = dep
resultsheet.Cells(tempi, WsecnrCol).value = dep & "_" & sec
resultsheet.Cells(tempi, WjtypeCol).value = varType
resultsheet.Cells(tempi, WspgCol).value = varKey
resultsheet.Cells(tempi, WsporgCol).value = "=VLOOKUP(H" & tempi & ",Spørgsmål!$D:$I,6,0)"
resultsheet.Cells(tempi, WtestCol).value = ""
resultsheet.Cells(tempi, Wsv1Col).value = colavg
resultsheet.Cells(tempi, Wsv2Col).value = (1 - colavg)
resultsheet.Cells(tempi, Wsv3Col).value = ""
resultsheet.Cells(tempi, WgrpCol).value = "=VLOOKUP(H" & tempi & ",Spørgsmål!$D:$I,4,0)"
totalposts = totalposts + 1
End If
Next
End If
IterateColumns = totalposts
End Function
'Function that gets the workbook for import
Function OpenWorkbook()
Dim pathString As String
Dim resultWorkbook As Workbook
pathString = Application.GetOpenFilename(fileFilter:="All Files (*.*), *.*")
' check if it's already opened
For Each wb In Workbooks
If InStr(pathString, wb.Name) > 0 Then
Set resultWorkbook = wb
Exit For
End If
Next wb
If Not found Then
Set resultWorkbook = Workbooks.Open(pathString)
End If
Set OpenWorkbook = resultWorkbook
End Function
'find column numbers for resultsheet instead of having to do this in every insert
Function setResultColVars(rsheet)
WyearCol = rsheet.UsedRange.Find("År").column
WmonthCol = rsheet.UsedRange.Find("Måned").column
WweekCol = rsheet.UsedRange.Find("Uge").column
WhospCol = rsheet.UsedRange.Find("Hospital").column
WdepCol = rsheet.UsedRange.Find("Afdeling").column
WsecCol = rsheet.UsedRange.Find("Afsnit").column
WdepnrCol = rsheet.UsedRange.Find("Afdelingsnr").column
WsecnrCol = rsheet.UsedRange.Find("Afsnitnr").column
WjtypeCol = rsheet.UsedRange.Find("Journaltype").column
WspgCol = rsheet.UsedRange.Find("spg").column
WsporgCol = rsheet.UsedRange.Find("spørgsmål").column
WtestCol = rsheet.UsedRange.Find("test").column
Wsv1Col = rsheet.UsedRange.Find("Svar 1").column
Wsv2Col = rsheet.UsedRange.Find("Svar 0").column
Wsv3Col = rsheet.UsedRange.Find("Svar 3").column
WgrpCol = rsheet.UsedRange.Find("Gruppering").column
End Function
Function sortSpgs(key, sheet, sortspg As Boolean)
If Not (sheet.UsedRange.Find(key) Is Nothing) Then
If (sortspg) Then
ResultsWindow.lstGenkendt.AddItem key
End If
sortSpgs = True
Else
If (sortspg) Then
ResultsWindow.lstUgenkendt.AddItem key
End If
sortSpgs = False
End If
End Function
Function Progress()
iProgress = iProgress + 1
Application.StatusBar = iProgress & "% Completed"
End Function
Difficult to debug without the source files.
I see the following potential problems:
GetRowRange: .UsedRange might return more columns than you expect. Check by pressing Ctrl-End in the worksheet and see where you end up
Some thing in your main routine - depsheet.UsedRange.Columns(1).Cells might just result in much more rows than expected
someRange.Value = "VLOOKUP(... will store the formula as text. You need .Formula = instead of .Value (this will not solve your long runtime but certainly avoid another bug)
In sortSpgs you add know or unknow items to a control. Not knowing if there's any event code behind these controls, disable events with Application.EnableEvents=False (ideally in the beginning of your main sub together with the .ScreenUpdating = False)
Also, set Application.Calculation = xlCalculationManual at the beginning and Application.Calculation = xlCalculationAutomatic at the end of your code
You're performing a lot of .Find - esp. in sortSpgs - this is potentially slow in large sheets, as it has to loop over quite some data, depending on the underlying range.
Generally, a few more "best practise remarks":
* Dim your variables with the correct types, same for returns of functions
* Use With obj to make the code cleaner. E.g. in setResulcolVars you could use With rsheet.UsedRange and remove this part in the following 15 or so lines
* In modules of small scope, it is okay to dim some variable with a module wide scope - esp. if you hand them over with every call. This will make your code much easier to read
Hope that helps a bit... mvh /P.
My guess is that Application.Screenupdating is the problem. You set to false inside the:
if Not (importsheet.UsedRange.Find("afdeling") Is Nothing) Then
block. So if the isn't the case then screenupdateing isn't disabled. you should move it to the beginning of the function.
you could also try to write the usedrange in an array, work with it , and write it back if needed.
code example
dim MyArr() as Variant
redim MyArray (1 to usedrange.rows.count, 1 to usedrange.columns)
MyArray=usedrange.value
'calculating with Myarray instead of ranges (faster)
usedrange.value=myarray 'writes changes back to the sheet/range
also, maybe you can use .match instead of .find, wich is faster.
with arrays you use application.match( SearchValue, Array_Name, False) 'false if for exact match
the same thing works for range.find() , becoming application.find()...
save first your master workbook under a new name before making such a big change...

Resources