Excel Queries from Excel Workbook located on OneDrive From Different Users - excel

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)

Related

Is there a resolution in VBA for the error Run-time error '429' when trying to connect to a website?

I am trying to create a VBA to download a google sheet into excel so I can compile stock market data daily. I would simply use power query for this but I am doing this on my personal laptop which is a mac and does not support power query. I am relatively new to coding so have been leaning on following online instructions. The instruction includes this:
Set objWebCon = CreateObject("MSXML2.XMLHTTP.3.0")
This line when ran creates an error message saying:
"
Run-time error '429':
ActiveX component can't create object
"
I think the issue lies within the fact that the instruction is based on a windows operating system. Any solution I've searched for is specific to windows operating systems.
Does anybody here know if I can change the "MSXML2.XMLHTTP.3.0" part of my code to fit it better to mac? Not sure if this is what needs to be done but any guidance would be super appreciated.
I attached my full code below but feel free to ignore it if not relavent. Thank you!!
Sub DownloadGoogleSheets()
Dim ShtUrl As String, Location As String, FileName As String
Dim objWebCon, objWrit As Object
'Sheet Url
ShtUrl = "https://docs.google.com/spreadsheets/d/1wpA_epxtlz96sxETqKttJwsy9Aubb15H8xslcSQ20T0/export?format=csv&id=1wpA_epxtlz96sxETqKttJwsy9Aubb15H8xslcSQ20T0" & gid = 1319327791
'Location
Location = ThisWorkbook.Path & "\" '/Users/[myName]/Desktop/Stock Analysis/n"
'FileName
FileName = "GoogleSheet.csv"
'Connection to Website
Set objWebCon = CreateObject("MSXML2.XMLHTTP.3.0")
'Writer
Set objWrit = CreateObject("ADODB.Stream")
'Connecting to the Website
objWebCon.Open "Get", ShtUrl, False
objWebCon.Send (ShtUrl)
'Once page is fully loaded
If objWebCon.Status = 200 Then
'Write the text of the sheet
objWrit.Open
objWrit.Type = 1
objWrit.Write objWebCon.ResponseBody
objWrit.Position = 0
objWrit.SaveToFile Location & FileName
objWrit.Close
End If
Set objWebCon = Nothing
Set objWrit = Nothing
End Sub

Access Type conversion failure importing from Excel

I'm trying to import an Excel to Access DB, and some customer numbers cannot be imported due to Type Conversion Failure. It is 12 entries out of 66 thousand. Normally the customer number is a number, but these 12 are strings like ABCDEFT001. I tried setting the field of the table to Long Text or Short text, they are still not imported (only to ImportError table). Do you know what else I can try?
Thank you very much in advance!
P.S. I'm trying to import using DoCmd.TransferSpreadsheet
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Inv level", "Path/to/file.xlsb", True, "Sheetname!"
This strategy links to the excel file, instead of directly importing it, and then selects data out of it and casts any fields that need it to the correct datatype.
Sub ImportFromExcel()
Dim pathToFile As String
Dim targetTableName As String
Dim sql As String
pathToFile = "C:\Path\To\File.xlsx"
targetTableName = "ImportResults"
'//create the link
DoCmd.TransferSpreadsheet acLink, _
acSpreadsheetTypeExcel12, _
targetTableName, _
pathToFile, _
True '//This part only if the excel file has field headers
'//import
sql = "SELECT Field1Name, CStr(CustNumber) AS CustNumber, Field3Name INTO NewImportTable FROM " & targetTableName
CurrentDb.Execute sql
'//remove the link
DoCmd.DeleteObject acTable, targetTableName
End Sub
***Two pitfalls of this code to be aware of:
1) You should delete any table with the name "NewImportTable" before running this code, or you'll get a "Table Already Exists" error.
2) If any errors happen in this Sub before you remove the link, you'll have an issue the next time it runs, as it will create a link called "ImportResults1" since "ImportResults" would still exist. The really scary thing is that no errors would be thrown here. It would create "ImportResults1" and then run your sql on "ImportResults"!!

VBA - Update Linked Table of an Access file from Excel

I am trying to change the linked table address from an Access file "Hey.accdb" using VBA coding from an Excel file.
I've coded the script below in my Excel file and it prompts the error "Object required" when I run it. Can someone please help me with this problem. I've been staring at it for too long. Thanks.
Sub RunMacroinAccesswithPara2()
Set Db = CreateObject("Access.Application")
Db.OpenCurrentDatabase "D:\Database1\Hey.accdb"
Db.Visible = True
Db.AutomationSecurity = msoAutomationSecurityLow
DoCmd.TransferDatabase TransferType:=acLink, _
DatabaseType:="Microsoft Access", _
DatabaseName:="V:\Reporting\Quarterly\2018Q2\JP\Data\04\Database\Valuation_Database.mdb", _
ObjectType:=acTable, _
Source:="Valuation_Database_Adjusted", _
Destination:="Valuation_Database_Adjusted"
End Sub
DoCmd belongs to the Access application object.
So use
Db.DoCmd.TransferDatabase ' etc.
Edit
To update the link, you need the TableDef object, set its .Connect property and run .RefreshLink.
See Linked table ms access 2010 change connection string

Running PeopleSoft Query with Excel VBA Hyperlink

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

PowerQuery - Folder Query import new files

If I have created a PowerQuery function that imports XML from a folder, how in the same excel file do I reuse the query when there are new files in the folder to only include data from those new files and append the data to the current table?
If you start a Power Query using From File / From Folder and browse to your folder, you will see each file represented as a row in a table, with columns such as Date modified. You can filter that list using Date/Time filters on Date modified or by something more complicated if necessary (post your specific requirements and I'll try to steer you in the right direction).
Once you have filtered the query to just the "new files", you can pass the [Content] column into your Function.
Finally Append a new query based on the saved Excel Table output from your pre-existing query together with the "new files" query above to get your combined output. The new query would be set to Load To / Only Create Connection.
you can watch a folder for file changes with a simple vba script that uses WMI to poll the directory contents every n seconds.
Something similar to this ...
Sub WatchDirectory(dir as string, every as integer)
Set wmisvc = GetObject("winmgmts:\\.\root\cimv2")
let query = "SELECT * FROM __InstanceOperationEvent " _
& "WITHIN " & every _
& " WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
& "TargetInstance.GroupComponent='Win32_Directory.Name=" _
& Chr(34) & dir & Chr(34) & "'"
Set events = wmisvc.ExecNotificationQuery(query)
Do While True
Set event = events.NextEvent()
if event.Class = "__InstanceCreationEvent" then
....
end if
Loop
For more info on wmi see https://sites.google.com/site/beyondexcel/project-updates/exposingsystemsecretswithvbaandwmiapi
For more details on file watching with WMI, see https://blogs.technet.microsoft.com/heyscriptingguy/2005/04/04/how-can-i-monitor-for-different-types-of-events-with-just-one-script/

Resources