Running PeopleSoft Query with Excel VBA Hyperlink - excel

I've used similar code below to run "public" PeopleSoft queries from Excel using VBA. When I look at the hyperlink produced from the code below, it is similar to the public queries we run with this method. The only difference is this is a "private" query. I can manually run the query in PeopleSoft with these same prompts and it runs and produces results like it is supposed to (32 rows). However, when I run this code from Excel, PeopleSoft opens, you sign in and it looks like the query runs. However, it doesn't return any results (0 rows). Is this there some twist with running "private" queries. Is it not possible to run "private" queries with this method? Any suggestions would be greatly appreciated as this has us stumped. Thanks for the help......
We are using Excel 2010, PeopleSoft 9.1 and PeopleTools 8.52 if that helps
Dim vFROMACCT As Date
Dim vTOACCT As Date
vFROMACCT = "07/01/2016"
vTOACCT = "07/21/2016"
vFROMACCT = Format(vFROMACCT, "MM/DD/YYYY")
vTOACCT = Format(vTOACCT, "MM/DD/YYYY")
vHypRoot = "http://pswebfsprd.myco.com/fsprd_1/EMPLOYEE/ERP/q/?ICAction=ICQryNameExcelURL=PRIVATE.CAR_SALES_1"
vHypLnk = vHypRoot
vHypLnk = vHypLnk & "&bind1=" & vFROMACCT
vHypLnk = vHypLnk & "&bind2=" & vTOACCT
With Worksheets("Sheet1")
.Hyperlinks.Add .Cells(10, 1), vHypLnk
.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
End With

If you are getting 0 results then the query is running. I believe your problem is with your date parameters. I was able to run a private query with a date parameter but I had to use the date in YYYY-MM-DD format.
&BIND1=2016-07-21
This was on DB2 so it may be different for your DB. If you need to use a format with slashes in it, ensure you encode the URL before submitting it. Here is a Stack Overflow question on urlencoding in VBA
My full URL was:
https://dev.removed.com/psp/mydev/EMPLOYEE/ERP/q/?ICAction=ICQryNameURL=PRIVATE.TEST_DS&BIND1=2016-07-21
Note: This was on PeopleTools 8.54.13 but should work on 8.52

Related

Excel Queries from Excel Workbook located on OneDrive From Different Users

Friends,
I currently am pulling data from an excel file located in OneDrive into my spreadsheet using the following source.
= Excel.Workbook(File.Contents("C:\Users\Bob Saggat\OneDrive - USS Enterprise\Prototype\InvestorsMasterProto.xlsm"), null, true)
I use the following code to successfully post data to files with different users from the OneDrive folder in VBA modules with the following code:
Workbooks.Open("C:\Users\" & Environ("username") & "\OneDrive - USS Enterprise\Prototype\OrdersMasterProto.xlsm")
I expected using Environ("username") in the Power Query Editor in the code for the source of the file to work.
= Excel.Workbook(File.Contents("C:\Users\" & Environ("username") & "\OneDrive - USS Enterprise\Prototype\InvestorsMasterProto.xlsm"), null, true)
When I do so I get the following error: Expression.Error: The name 'Environ' wasn't recognized. Make sure it's spelled correctly.
What is the solution here?
Some GoogleFu suggests I host the file on a SharePoint instead of in OneDrive but I have absolutely no experience in SharePoint and I presume there is a simple solution I am missing.
As always, your wisdom and kindness is greatly appreciated.
Thank You
--
Now, I call this module on load to find the username and put it into a named ranged. This works.
Sub GetUsernameForDataSource()
Dim OrderRunTemplate As Worksheet
Set OrderRunTemplate = ThisWorkbook.Worksheets("Order Run Template")
LocalUsername = Environ("username")
'May need to clear the CurrentUser named ranged first then add the user so it doesn't add multiple users
'Adding LocalUsername to named range to use as source in PowerQuery
ThisWorkbook.Names.Add Name:="CurrentUser", _
RefersTo:=LocalUsername
End Sub
Yet when I go into PowerQuery and enter the following
= Excel.Workbook(File.Contents("C:\Users\" & Excel.CurrentWorkbook(){[Name="CurentUser"]}[Content]{0}[Column1] & "\OneDrive - USS Enterprise\Prototype\InvestorsMasterProto.xlsm"), null, true)
I get the error:
Expression.Error: We couldn't find an Excel table named 'CurrentUser'.
Details:
CurrentUser
Any suggestions?
assuming you can get the value of Environ("username") into a named range such as abc, then you can read that named range in powerquery using
Excel.CurrentWorkbook(){[Name="abc"]}[Content]{0}[Column1]
and in your code as
= Excel.Workbook(File.Contents("C:\Users\" & Excel.CurrentWorkbook(){[Name="abc"]}[Content]{0}[Column1] & "\OneDrive - USS Enterprise\Prototype\InvestorsMasterProto.xlsm"), null, true)

Using VBA to get data from SAS and limit the data set

I need to import data from SAS to excel via VBA. The import needs to run eg. on workbookOpen or Worksheet_BeforeDoubleClick or it can be called in any macro. This is solved in the below code:
Sub GetSASdata()
Dim obConnection As ADODB.Connection
Dim obRecordset As ADODB.Recordset
Dim i As Integer
Set obConnection = New ADODB.Connection
' Do not get stuck on the choice of connection provider.
obConnection.Provider = "sas.LocalProvider"
obConnection.Properties("Data Source") = "C:\path\"
obConnection.Open
Set obRecordset = New ADODB.Recordset
obRecordset.Open "MySAStable", obConnection, adOpenDynamic, adLockReadOnly, ADODB.adCmdTableDirect
'add header row
Cells(1, 1).Select
For i = 0 To obRecordset.Fields.Count - 1
ActiveCell.Offset(0, i).Value = obRecordset.Fields(i).Name
Next i
obRecordset.MoveFirst
obRecordset.Filter = "Weight > 0"
Cells(2, 1).Select
ActiveCell.CopyFromRecordset obRecordset, 100
obRecordset.Close
Set obRecordset = Nothing
obConnection.Close
Set obConnection = Nothing
End Sub
In this example I have restricted the output to be only the first 100 rows. However, the original data set is 1.4 m rows and 150 columns, and I want to be able to restrict the data import to only take columns that I define and rows which meet certain criteria. In sql terms:
select col1, col2, col10, col11 from MySAStable where code = MyCode and Date > MyDate
But I cannot find a way to do it. The first criteria is that the code should run entirely from Excel.
I have experimented some with obRecordset.Filter but the performance is poor. It takes forever. So idealy I would like to import only the data that I need. Is there a way to do this?
The
obConnection.Provider = "sas.LocalProvider"
is arbitrary. I found an example online, tested it and it worked. If someone has an answer to my problem that involves a different connection type, i am still interested to know. Very idealy the code can also be run by users who do not have SAS installed on their computer (but have access to the folder where data is placed.)
Thank you for any help
I have used two methods to read SAS data from within Excel.
The first uses SAS Add-In to MS Office. Do you have this product?
You can define the source with filters, and when the user opens the workbook, it will automatically refresh agains the datasource. You can also automate the refresh task with VBA code.
Secondly, I have done it with a Stored Process. If you have a stored process server, you can set up a web query in Excel and read the Stored Process that way, using any filter you need.

Use Excel spreadsheet from within Access

I have an Excel Spreadsheet that calculates a risk (of perioperative mortality after aneurysm repair) based on various test results.
The user inputs the test results into the spreadsheet (into cells) and then out comes a set of figures (about 6 results) for the various models that predict mortality. The spreadsheet acts as a complex function to produce the results one patient at a time.
I also have a (separate) access database holding data on multiple patients - including all the data on test results that go into the spreadsheet. At the moment I have to manually input this data into the spreadsheet, get the results out and then manually enter them onto the database.
Is there a way of doing this automatically. Ie can I export data1, data2, data3... from Access into the spreadsheet to the cells where the data needs to be input and then get the results (result1, result2, result3...) from the cells where the results are displayed ported back into access.
Ideally this could be done live.
I suppose I could try to program the functionality of the spreadheet into a complex function in access, but if I'm honest, I am not really sure how the algorithm in the spreadsheet works. It was designed by anaesthetists who are much cleverer than me....
Hope this makes sense. Any help much appreciated.
Chris Hammond
It's possible to automate Excel from Access.
Const cstrFile As String = "C:\SomeFolder\foo.xls"
Dim xlApp As Object
Dim xlWrkBk As Object
Dim xlWrkSt As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Workbooks.Open cstrFile, ReadOnly:=True
Set xlWrkBk = xlApp.Workbooks(1)
Set xlWrkSt = xlWrkBk.Worksheets(1)
With xlWrkSt
.Range("A1") = 2
.Range("A2") = 19
Debug.Print .Range("A3")
End With
xlWrkBk.Close SaveChanges:=False
However, that seems like it would be cumbersome to repeat for each row of an Access table and I'm uncertain whether doing that live is reasonable.
I would try to adapt the Excel calculations to Access VBA functions and use those custom functions in an Access query. But I don't know how big of a task that would be. I suggest you shouldn't be scared off the the anaesthetists' cleverness; that doesn't mean they actually know much more about VBA than you. At least look to see whether you can tackle it.
To push the data back to Access, you can insert data from within the Excel VBA as follows:
dim val as variant
dim db as DAO.Database
val=thisworkbook.range("a1").value
set db=OpenDatabase("c:\myAccessDB.accdb")
db.execute "insert into patientData (someField) values (" & val & ")",dbFailOnError
db.Close
You'll need to add a reference to the Microsoft Office Access Database Engine Object Library.
Not sure to perfectly understand what you want, but if you just want to export the results of a query to a spreadsheet, you could use the following:
Private Sub ExportAccessDataToExcel()
Dim SqlString As String
SqlString = "CREATE TABLE testMeasurements (TestName TEXT, Status TEXT)"
DoCmd.RunSQL (SqlString)
SqlString = "INSERT INTO testMeasurements VALUES('Average Power','PASS')"
DoCmd.RunSQL (SqlString)
SqlString = "INSERT INTO testMeasurements VALUES('Power Vs Time','FAIL')"
DoCmd.RunSQL (SqlString)
SqlString = "SELECT testMeasurements.TestName, testMeasurements.Status INTO exportToExcel "
SqlString = SqlString & "FROM testMeasurements "
SqlString = SqlString & "WHERE (((testMeasurements.TestName)='Average Power'));"
DoCmd.RunSQL (SqlString)
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel7, "exportToExcel", "C:\TestMeasurements.xls", True, "A1:G12"
End Sub
Source: http://www.ehow.com/how_7326712_save-access-query-excel-vba.html
This could be done either directly from the database or from Excel (you would need to open the database with Excel VBA to do so, but most of the Office Suite products interact well with each other).
If you want to push the data of your spreadsheet into an Access database, that's different. You just have to open the database and loop through INSERT query. Here is a quick example, you just need to add the loop:
Dim db as DAO.Database
Set db = OpenDatabase(myDataBase.mdb)
Call db.Execute("INSERT INTO myTable (Field1, Field2) VALUES('Value1', 'Value2')")

Format a cell as arbitrary currency regardless of locale, using VBA

This is really bugging me as it seems pretty illogical the way it's working.
I have a macro to format a cell as a currency using a bit of code to obtain the currency symbol.
Here is the code involved:
Dim sym As String
sym = reportConstants(ISOcode)
'Just use the ISO code if there isn't a symbol available
If sym = "" Then
sym = ISOcode
End If
With range(.Offset(0, 3), .Offset(3, 3))
.NumberFormat = sym & "#,##0;(" & sym & "#,##0)"
Debug.Print sym & "#,##0;(" & sym & "#,##0)"
End With
reportConstants is a dictionary object with currency symbols defined as strings. E.g. reportConstants("USD") = "$". This is defined earlier in the macro.
When the macro runs it gets the ISO code and should then format the cell with the corresponding currency symbol.
When I run it in one instance the ISO code is "USD" - so sym is defined as "$" - but it still formats the cell with a pound sign (£). When I debug.print the format cell string it shows $#,##0;($#,##0) so, as long as I got my syntax correct, it should use a dollar sign in the cell. But it uses a £ sign instead. (I am running a UK version of excel so it may be defaulting to £-sign, but why?)
Any help greatly appreciated.
I just recorded a macro to set the format to $xx.xx and it created this: [$$-409]#,##0.00. Looks like the -409 localises the currency to a particular country; it works without it - try changing yours to .NumberFormat = "[$" & sym & "]#,##0.00"
Btw guess I read your question somewhat after posting ;) Excel is well influenced by the regional settings of your computer for currency, language, dates... Using numberformat can force it to keep the sign you require. if it is a matter of rounding up you can try to: On Excel 2010, go to File - Options - Advanced and scroll down to "When calculating this workbook" and click on the "set precision as displayed" and OK out. 
Try this: given your values are numerics/ integers/decimals....
Range("a2").Style = "Currency"
Or you can use format:
Format(value, "Currency")
Format(Range(a2).value, "Currency")
References:
http://www.mrexcel.com/forum/excel-questions/439331-displaying-currency-based-regional-settings.html
http://www.addictivetips.com/microsoft-office/excel-2010-currency-values/
(PS: I am on mobile, you may try these two links)

MS Access & Excel: Turning a query with dynamic parameters into something useful

I got stuck in the problem beneath, because I don´t use Access or Excel much and I have some basic programming language. So here's the deal:
I just made a fairly simple database in MS Access (2007) with a nice query to retrieve data, depending on which parameters you pass. In Excel (2007), I have this big 'template' which basically has parameters for the query. These parameters change per column & per row!
Perhaps superfluously, e.g.
column A contains paramA (10 different options)
column B contains paramB (8 different options)
column C contains paramC (2 different options)
What I'd like to do is to fill this template with dynamic data from Access, minding the continously changing parameters.
e.g.
column D contains Query (ParamA, ParamB, ParamC)
Best way to go I think is to make a (inline?) function that retrieves results from the query, also passing the parameters depending on the relative cell position. And this function is then copied as a normal inline excel function (like: SUM()).
I just don't know how to call /execute an MS Access query from inside an Excel Macro function.
Could someone help me with it? Thank you very much in advance!
A few notes.
Dim cn As Object
Dim rs As Object
''See: http://www.connectionstrings.com/access
strFile = "C:\Docs\AccessDB.mdb"
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";User Id=admin;Password=;"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT SomeField, OtherField FROM SomeTable " _
& "WHERE SomeText='" & Range("A1") & "'"
rs.Open strSQL, cn
s = rs.GetString
MsgBox s
'' Or
Sheets("Sheet2").Cells(2, 1).CopyFromRecordset rs
To add to Remou's answer also see
Modules: Sample Excel Automation - cell by cell which is slow and
Modules: Transferring Records to Excel with Automation
Late binding means you can safely remove the reference and only have an error when the app executes lines of code in question. Rather than erroring out while starting up the app and not allowing the users in the app at all. Or when hitting a mid, left or trim function call.
This also is very useful when you don't know version of the external application will reside on the target system. Or if your organization is in the middle of moving from one version to another.
For more information including additional text and some detailed links see the "Late Binding in Microsoft Access" page

Resources