This site has moved here.
You can find this page here on the new site.
The Sheets V4 API is a very nice piece of work that exposes almost all of the Sheets object model in a REST API. Here’s a VBA wrapper for that API. I’ll add to it over time, but this version allows you to do this — in just a few lines of VBA.
- Authenticate to Sheets using Oauth2 from Excel
- Push sheet data to google
- Pull sheet data from google
- Get a list of sheets in a Google Spreadsheet
Examples
Let’s get straight down to some examples. For the purposes of demo, I’ve made a sample workbook — sheetsAPI.xlsm — which you can get from the downloads page, under the data manipulation folder.
It has two buttons — one to get this sheet from google, and another to send it there.
Here’s the code behind the buttons.
You can pass the name of the sheet (or a list of sheets separated by commas) to pull the data from Google. Here’ im getting the activesheet.
Public Sub getThisSheet()
Dim result As cjobject
Set result = getStuffFromSheets(getMySheetId(), ActiveSheet.NAME)
If (Not result.child("success").value) Then
MsgBox ("failed on sheets API " + result.child("response"))
Exit Sub
End If
writeToSheets result.child("data").children(1).child("valueRanges"), True
End Sub
And the same principle to push to google
Public Sub putThisSheet()
Dim result As cjobject
Set result = putStuffToSheets(getMySheetId(), ActiveSheet.NAME)
If (Not result.child("success").value) Then
MsgBox ("failed on sheets API " + result.child("response"))
Exit Sub
End If
End Sub
The sheet ID is the Google Drive ID of the workbook to write or read to. In my example, I’m simply returning a fixed id for a test spreadsheet. You may want to implement a form or a picker to select from multiple sheets. In any case you’ll need to change this to whatever your own sheet id is.
Private Function getMySheetId() As String
'// make this into your own sheet id
getMySheetId = "1V54F5b1e1bOcJXJ_McRkpyJ5Dx_ndGnjdiZpBeyA4L0"
End Function
Authorization
People usually find OAUTH2 a little scary. I’ve tried to simplify it as much as possible. Here’s what you need to do.
- go to the google developers console (you can use the project associated with your spreadsheet, or as I do — create a new project that can be used for all spreadsheet activities).
- authorize the Sheets API
- generate some credentials
- copy them into this one off function, run it and allow it to access your sheets
- after that you can delete the one off function. It won’t need to ask you again.
Private Function sheetsOnceOff()
getGoogled "sheets", , _
"109xxxxxxxxxxieuu2q3.apps.googleusercontent.com", _
"CVgxxxxxxxxxePfe"
End Function
A note on different versions of windows/IE and locked down PCS
Behind the scene, the OAUTH2 process is fairly complex, and may not work on various combinations of Older IE and Windows. Some enterprises also lock down Windows so you can’t POST from Excel, or you can’t write to the registry, and various other combinations. getGoogled will only work if it can write to the registry, get to the internals of the IE DOM structure, and POST http requests to the google domain.
When getGoogled has completed successfully, you’ll find a registry entry for any scopes you’ve used. Note that you can have multiple entries if you have done some of the other integrations on this site that also use OAUTH2. The example above will create an entry for ‘scope_sheets’ that look like this under the xLiberation key. If you cannot get this to happen for some reason of lockdown or version combination, then you won’t be able to get any further until that’s solved. Look at the G+ community for others who have found various ways to get round lock down problems in their environment.
The console
Enable this API
Create a new oauth2 client ID
Choose other and then create
Copy credentials and put them in the one off function
Run the one off function, and you’ll get something like this
And that’s it — you can use the example once you create the Google Sheet you want to play with and enter its id. You delete the once off function now if you like.
Compatibility
This will work on Windows 10 with Excel 2016. It will probably also work with older versions of both Windows and Excel too. It will need a few tweaks to work on Excel for Mac. If anybody would like to help with a Mac version then please ping me I can point you in the correct version.
Some older installations have missing modern DLL versions, or some objects are blocked by policy. I’ve added some workarounds to to use different objects for external access from excel, as they have changed over time. If you get an error about xmlhttp, then if you can find out which xmlhttp object you do have installed, or is not blocked, then you can extend the function below (in the cBrowser class), to use it instead. If you do, then please leave feedback on the community so it can be implemented for others too, so more versions can be covered.
Private Function getHttpObject(Optional timeout As Long = 0) As Object
'// some installation dont have server object installed, so fall back
Dim ob As Object
On Error GoTo missing
Set ob = CreateObject("Msxml2.ServerXMLHTTP.6.0")
ob.setOption 2, ob.getOption(2) - SXH_SERVER_CERT_IGNORE_CERT_DATE_INVALID
' can have change of timeout for complex/long queries
If timeout <> 0 Then
ob.setTimeouts 0, 30 * 1000, 30 * 1000, timeout * 1000
End If
Set getHttpObject = ob
Exit Function
missing:
On Error GoTo screwed
Set ob = CreateObject("Msxml2.XMLHTTP.6.0")
Debug.Print "falling back to client xmlhttp - server is not installed on this machine"
Set getHttpObject = ob
Exit Function
screwed:
MsgBox ("cant find either server or client xmlhttp - there missing files from your windows installtion")
Exit Function
End Function
More
I’ll be adding to this api over time to be able to further collaborate between the two platforms.
An example of using Google APIs with VBA-Web is included in the examples/
folder of the project. Some details:
Authentication
There are many approaches to using Google’s OAuth 2.0 authentication, but for use with VBA-Web, none that require a callback url could be used. That limits the authentication approach to Installed Application / Device.
- Go to Google’s API Console to create a new application with Google. In the Client ID Settings section, select Installed application and Other. Store the generated Client Id and Secret.
- Determine the desired scope for your application. For example, in order to access Google Analytics data, this needs to be defined in the scope as
https://www.googleapis.com/auth/analytics.readonly
. In general, each scope is prefixed byhttps://www.googleapis.com/auth/
with the specific scope then added. For a list of available scopes, visit the Google OAuth 2.0 Playground - Add the
GoogleAuthenticator
class to your project and set it up as follows:
Dim Auth As New GoogleAuthenticator Auth.Setup _ ClientId:="ClientId", _ ClientSecret:="ClientSecret" Auth.Scope = Array("https://www.googleapis.com/auth/analytics.readonly") Auth.Login Set Client.Authenticator = Auth
Example Request
With authentication setup for your client, you can use the normal request configuration. Here’s an example of the desired url for retreiving Google Analytics data and how to setup the request:
' Desired request: GET https://www.googleapis.com/analytics/v3/data/ga ' ?ids=ga:12345 ' &start-date=2008-10-01 ' &end-date=2008-10-31 ' &metrics=ga:visits,ga:bounces ' Client.BaseUrl = "https://www.googleapis.com/analytics/v3/" Public Function AnalyticsRequest(ProfileId As String, StartDate As Date, EndDate As Date) As RestRequest Set AnalyticsRequest = New WebRequest AnalyticsRequest.Resource = "data/ga" AnalyticsRequest.Method = WebMethod.HttpGet AnalyticsRequest.AddQuerystringParam "ids", "ga:" & ProfileId AnalyticsRequest.AddQuerystringParam "start-date", Format(StartDate, "yyyy-mm-dd") AnalyticsRequest.AddQuerystringParam "end-date", Format(EndDate, "yyyy-mm-dd") AnalyticsRequest.AddQuerystringParam "metrics", "ga:visits,ga:bounces" End Function
Links:
- Using OAuth 2.0 to Access Google APIs, Installed Application / Devices
- Using OAuth 2.0 for Installed Applications
- Google OAuth 2.0 Playground
In this article, we will create an Excel function to calculate the distance between two addresses using the Google Maps directions API. This will allow you to get the travel time between the two locations. The format of the function will be as follows: =TRAVELTIME(origin, destination, api_key)
, =TRAVELDISTANCE(origin, destination, apikey)
. The origin and destination will be strings, and can be either an exact address or the name of a place. In order to use the function, an API key is required. The “Getting Started” page can help you with this: http://bit.ly/googlemapsgettingstarted. Create a new project and make sure the Directions API is added.
Step 1: Create a new macro file and add VBA-JSON
Because the Google Maps Directions API is a JSON API, we will use VBA-JSON to make it easy to use the results from the web request. You can download the latest version from here: https://github.com/VBA-tools/VBA-JSON/releases. Download and extract the zip file. Then, open your macro file. Open the Visual Basic Editor (Alt + F11).
In order to import the VBA-JSON file, go to File > Import File… (Ctrl + M). Select JsonConverter.bas
. A JsonConverter module will appear in the sidebar.
Next, make sure the appropriate references are enabled. Go to Tools > References… In addition to the references already selected, check off “Microsoft Scripting Runtime” (for Dictionary support needed by VBA-JSON) and “Microsoft WinHTTP Services, version 5.1” (to make the HTTP request to the API). If you require support for Excel for Mac, you will need to install VBA-Dictionary from the author of VBA-JSON. More details can be found at the bottom of the project homepage: https://github.com/VBA-tools/VBA-JSON.
Step 2: Create the functions
With the references configured, we can now write the code for the function. The code is relatively simple. It is simply takes the three parameters and formats them into a web request. The response of the web request is then parsed by VBA-JSON and the relevant variable returned. Note that the request may return multiple routes, but then function simply returns the time of the first route. The default mode is driving, but refer to the Directions API documentation for information on other modes and adjust the strURL variable accordingly.
To insert the code, create a new module with Insert > Module. Then paste the following code:
' Returns the number of seconds it would take to get from one place to another Function TRAVELTIME(origin, destination, apikey) Dim strUrl As String strUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey Set httpReq = CreateObject("MSXML2.XMLHTTP") With httpReq .Open "GET", strUrl, False .Send End With Dim response As String response = httpReq.ResponseText Dim parsed As Dictionary Set parsed = JsonConverter.ParseJson(response) Dim seconds As Integer Dim leg As Dictionary For Each leg In parsed("routes")(1)("legs") seconds = seconds + leg("duration")("value") Next leg TRAVELTIME = seconds End Function ' Returns the number of seconds it would take to get from one place to another Function TRAVELDISTANCE(origin, destination, apikey) Dim strUrl As String strUrl = "https://maps.googleapis.com/maps/api/directions/json?origin=" & origin & "&destination=" & destination & "&key=" & apikey Set httpReq = CreateObject("MSXML2.XMLHTTP") With httpReq .Open "GET", strUrl, False .Send End With Dim response As String response = httpReq.ResponseText Dim parsed As Dictionary Set parsed = JsonConverter.ParseJson(response) Dim meters As Integer Dim leg As Dictionary For Each leg In parsed("routes")(1)("legs") meters = meters + leg("distance")("value") Next leg TRAVELDISTANCE = meters End Function
Save the file. You should now be able to use the functions from within Excel. Place your API key in cell A1, then try the following: =TRAVELTIME("24 Sussex Drive Ottawa ON", "Parliament Hill", A1)
. This returns a travel time of about 435 seconds. If you would like this to be displayed in minutes and seconds, try this function: =FLOOR.MATH(A8/60)&" minutes "&MOD(A8, 60)&" seconds"
where A8 is the cell with the travel time in seconds. This prints a helpful “7 minutes 15 seconds” for the 24 Sussex example. We can also find the distance. Try the following: =TRAVELDISTANCE("24 Sussex Drive Ottawa ON", "Parliament Hill", A1)
. It returns a distance of 2667 meters. Convert to kilometers with this: =ROUND(A9/1000, 1)&" km"
.
Note: The Google Maps Directions API always returns distances in meters. Convert to KM or Miles as you wish. This can be done in Excel or by modifying the functions in VBA.
That’s it! You should now have a working travel time function. All you need now is a list of addresses to use it with. If you would like to pull a list from the web or local JSON file, check out Import JSON Data in Excel 2016 or 2019 or Office 365 using a Get & Transform Query.
The Google Sheets V4 API is a very nice piece of work that exposes almost all of the Sheets object model in a REST API. Here’s a VBA wrapper for that API. I’ll add to it over time, but this version allows you to do this – in just a few lines of VBA.
- Authenticate to Sheets using Oauth2 from Excel
- Push sheet data to google
- Pull sheet data from google
- Get a list of sheets in a Google Spreadsheet
Examples
Let’s get straight down to some examples. For the purposes of demo, I’ve made a sample workbook – sheetsAPI.xlsm – which you can get from the downloads page, under the data manipulation folder.
It has two buttons – one to get this sheet from google, and another to send it there.
Here’s the code behind the buttons.
You can pass the name of the sheet (or a list of sheets separated by commas) to pull the data from Google. Here’ im getting the activesheet.
Public Sub getThisSheet() Dim result As cjobject Set result = getStuffFromSheets(getMySheetId(), ActiveSheet.NAME) If (Not result.child("success").value) Then MsgBox ("failed on sheets API " + result.child("response")) Exit Sub End If writeToSheets result.child("data").children(1).child("valueRanges"), True End Sub
And the same principle to push to google
Public Sub putThisSheet() Dim result As cjobject Set result = putStuffToSheets(getMySheetId(), ActiveSheet.NAME) If (Not result.child("success").value) Then MsgBox ("failed on sheets API " + result.child("response")) Exit Sub End If End Sub
The sheet ID is the Google Drive ID of the workbook to write or read to. In my example, I’m simply returning a fixed id for a test spreadsheet. You may want to implement a form or a picker to select from multiple sheets. In any case you’ll need to change this to whatever your own sheet id is.
Private Function getMySheetId() As String'// make this into your own sheet id getMySheetId = "1V54F5b1e1bOcJXJ_McRkpyJ5Dx_ndGnjdiZpBeyA4L0" End Function
People usually find OAUTH2 a little scary. I’ve tried to simplify it as much as possible. Here’s what you need to do.
- go to the google developers console (you can use the project associated with your spreadsheet, or as I do – create a new project that can be used for all spreadsheet activities).
- authorize the Sheets API
- generate some credentials
- copy them into this one off function, run it and allow it to access your sheets
- after that you can delete the one off function. It won’t need to ask you again.
Private Function sheetsOnceOff() getGoogled "sheets", , _ "109xxxxxxxxxxieuu2q3.apps.googleusercontent.com", _ "CVgxxxxxxxxxePfe" End Function
A note on different versions of windows/IE and locked down PCS
Behind the scene, the OAUTH2 process is fairly complex, and may not work on various combinations of Older IE and Windows. Some enterprises also lock down Windows so you can’t POST from Excel, or you can’t write to the registry, and various other combinations. getGoogled will only work if it can write to the registry, get to the internals of the IE DOM structure, and POST http requests to the google domain.
When getGoogled has completed successfully, you’ll find a registry entry for any scopes you’ve used. Note that you can have multiple entries if you have done some of the other integrations on this site that also use OAUTH2. The example above will create an entry for ‘scope_sheets’ that look like this under the xLiberation key. If you cannot get this to happen for some reason of lockdown or version combination, then you won’t be able to get any further until that’s solved. Look at the Gitter community for others who have found various ways to get round lock down problems in their environment.
The console
Enable this API
Create a new oauth2 client ID
Choose other and then create
Copy credentials and put them in the one off function
Run the one off function, and you’ll get something like this
And that’s it – you can use the example once you create the Google Sheet you want to play with and enter its id. You delete the once off function now if you like.
Compatibility
This will work on Windows 10 with Excel 2016. It will probably also work with older versions of both Windows and Excel too. It will need a few tweaks to work on Excel for Mac. If anybody would like to help with a Mac version then please ping me I can point you in the correct version.
Some older installations have missing modern DLL versions, or some objects are blocked by policy. I’ve added some workarounds to to use different objects for external access from excel, as they have changed over time. If you get an error about xmlhttp, then if you can find out which xmlhttp object you do have installed, or is not blocked, then you can extend the function below (in the cBrowser class), to use it instead. If you do, then please leave feedback on the community so it can be implemented for others too, so more versions can be covered.
Private Function getHttpObject(Optional timeout As Long = 0) As Object '// some installation dont have server object installed, so fall back Dim ob As Object On Error GoTo missing Set ob = CreateObject("Msxml2.ServerXMLHTTP.6.0") ob.setOption 2, ob.getOption(2) - SXH_SERVER_CERT_IGNORE_CERT_DATE_INVALID ' can have change of timeout for complex/long queries If timeout <> 0 Then ob.setTimeouts 0, 30 * 1000, 30 * 1000, timeout * 1000 End If Set getHttpObject = ob Exit Function missing: On Error GoTo screwed Set ob = CreateObject("Msxml2.XMLHTTP.6.0") Debug.Print "falling back to client xmlhttp - server is not installed on this machine" Set getHttpObject = ob Exit Function screwed: MsgBox ("cant find either server or client xmlhttp - there missing files from your windows installtion") Exit Function End Function
More
I’ll be adding to this api over time to be able to further collaborate between the two platforms.
Why not join our forum, follow the blog or follow me on Twitter to ensure you get updates when they are available.
Содержание
- Google Drive API Using Excel VBA
- With Minimal Background in Both Google Drive API v3 and Excel 2016 VBA
- What’s in This Article?
- A | What’s an API?
- B | Authentication vs Authorization
- C | What is OAuth?
- D | Owner of Personal Data Resource
- E | Real-time Editing
- F | Client-Server Model
- G | OAuth 2.0 for Client-side Web Applications
- H | The Implicit Grant Flow
- K | Using Google OAuth Playground
- M | A Simple .NET Console Application
- N | Google API Client Libraries
- P | Calling .NET Methods from Excel VBA
- X | Pending Information
- Отправка данных из *.XLSX в Google Sheets
- Задача
- Подготовительный этап, в наличии имеем:
- Практическая часть:
- Заключение
- Google Places Details to Excel with VBA
- 2 Answers 2
Google Drive API Using Excel VBA
With Minimal Background in Both Google Drive API v3 and Excel 2016 VBA
How can a program in Excel 2016 VBA interact with files in Google Drive using its API? In an attempt to answer this question, this article walks an absolute beginner from zero background to efficient user of both Google Drive API and Excel 2016 VBA. The complexity of the information presented herein will increase drastically as you leave the first half behind.
What’s in This Article?
- A | What’s an API?
- B | Authentication vs Authorization
- C | What is OAuth?
- D | Owner of Personal Data Resource
- E | Real-time Editing
- F | Client-Server Model
- G | OAuth 2.0 for Client-side Web Applications
- H | The Implicit Grant Flow
- K | Using Google OAuth Playground
- M | A Simple .NET Console Application
- N | Google API Client Libraries
- P | Calling .NET Methods from Excel VBA
A | What’s an API?
The graphical user interface (GUI) is a form of user interface that allows users to interact with electronic devices through graphical icons and audio indicator such as primary notation, instead of text-based user interfaces, typed command labels or text navigation. | Tell me more
Application programming interface (API) a set of functions and procedures allowing the creation of applications that access the features or data of an operating system, application, or other service. | Tell me more
Google Drive is a file storage and synchronization service developed by Google. Launched on April 24, 2012, Google Drive allows users to store files on their servers, synchronize files across devices, and share files. | Tell me more
To use Google Drive using a browser, go to https://drive.google.com/ using your Gmail account. While there, you can use its GUI to upload your files from your computer to your Google Drive. Using its GUI, you can also give your friends access to your folder and its files in your Google Drive.
When an Excel 2016 VBA program needs to do the same and, on behalf of its users, interact with their Google Drive, it has to use the drive’s API instead of its GUI. In simple words, GUI is for human users and API is for machine users.
Access to a system is protected by authentication and authorization, and they are frequently used in conjunction with each other. Authentication is the process of verifying the user’s identity. After the user’s identity is authenticated, authorization kicks in. Security questions, for example, can add an extra layer of certainty to your authentication process. Security questions are an alternative way of identifying your customers when they have forgotten their password, entered the wrong credentials too many times, or tried to log in from an unfamiliar device or location.
Authorization is the process of verifying the user’s rights allowing appropriate access to the protected resources, be they data, functionality, or both. In some cases, there is no authorization; any user may be use a resource or access a file simply by asking for it. Most of the web pages on the Internet require no authentication or authorization.
Encryption involves the process of transforming data so that it is unreadable by anyone who does not have a decryption key. Encryption is used to protect, for example, a person’s credit card and personal information when it is sent over the Internet to the airline. The company encrypts the customer’s data so that it will be safer from interception in transit. Airports need to authenticate that the person is who he or she says she is and has purchased a ticket, before giving him or her a boarding pass. A flight attendant must authorize a person so that person can then see the inside of the plane and use the resources the plane has to fly from one place to the next. | Tell me more
C | What is OAuth?
Pronounced as oh-auth, OAuth (Open Authorization) is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords. Generally, OAuth provides to clients a “secure delegated access” to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. | Tell me more
OAuth is an authorization protocol, rather than an authentication protocol. It is an open standard protocol for authorization of an application for using user information. Using OAuth on its own as an authentication method may be referred to as pseudo-authentication. The communication flow is explained on this page here.
D | Owner of Personal Data Resource
When you create a Gmail account, you become an owner of your personal data resource. The data resource is information created by, used by or gathered by the data owner in order to conduct day to day business. Data resources are usually stored in databases under a database management system.
Attached to your Gmail account is a limited amount of your personal data resource. To store even more personal data, use Google Drive. In order to use Google Drive, you will need a Google account. Creating a Google account will automatically create a Gmail email. Once you’ve set up your Google account, you can access Google Drive by going to http://drive.google.com in your web browser. As you begin to upload and create files you’ll need to know how to view, manage, and organize them in the interface.
Using your Gmail address, you’re the owner of the personal data resource found inside your Google Drive.
E | Real-time Editing
While using the GUI of Google Drive, you can create a new document using Google Docs format.
You can edit a document in Google Docs format by using the GUI of Google Docs, which is the Google Document Editor (GDE).
You can authorize several other Google account holders to have read/write access to your Google document.
All authorized users can edit the same Google document at the same time. This is referred to as real-time editing.
In this case, Google Docs is the client application while Google Drive is the server application.
F | Client-Server Model
Client–server model is a distributed application structure that partitions tasks or workloads between the providers of a resource or service, called servers, and service requesters, called clients. Often clients and servers communicate over a computer network on separate hardware, but both client and server may reside in the same system. A server host runs one or more server programs, which share their resources with clients. A client does not share any of its resources, but it requests content or service from a server. Clients therefore initiate communication sessions with servers, which await incoming requests. Examples of computer applications that use the client–server model are Email, network printing, and the World Wide Web. | Tell me more
In few words, the Internet primarily uses a client-server model. The web browser is the client. The web server is the server. That a web server is hosted elsewhere (in the cloud) does not change the fact that the relationship between the web browser and the web server is a client-server relationship.
G | OAuth 2.0 for Client-side Web Applications
OAuth 2.0 allows users to share specific data with an application while keeping their usernames, passwords, and other information private. For example, an application can use OAuth 2.0 to obtain permission from users to store files in their Google Drives. | Tell me more
This OAuth 2.0 flow is called the implicit grant flow; see section G, below, or see this web sequence diagram here. It is designed for applications that access APIs only while the user is present at the application. These applications are not able to store confidential information.
In this flow, your app opens a Google URL that uses query parameters to identify your app and the type of API access that the app requires. You can open the URL in the current browser window or a popup. The user can authenticate with Google and grant the requested permissions. Google then redirects the user back to your app. The redirect includes an access token, which your app verifies and then uses to make API requests. |Tell me more
H | The Implicit Grant Flow
K | Using Google OAuth Playground
For a demo, do the following:
- Using the test email, chuckday402@gmail.com, open the Google Drive at https://drive.google.com/drive/u/1/my-drive
- Delete all untitled documents in Chuck’s drive.
- Select the gear button to then select the commands Settings, then Manage apps.
- Scroll around to find “ OAuth 2.0 Playground”; if found, click on the Options button then select “Disconnect from Drive” and disconnect.
- In a new Browser tab, go to the playground at https://developers.google.com/oauthplayground/
- Press on the X button near the top to reset or clear the playground.
- In the first step selecting and authorizing API, scroll down and look for the node “Drive API v3”.
- Expand the node then select the item “https://googleapis.com/auth/drive.file”.
- Press the button [Authorize APIs]
You will be brought to a URL similar to the following:
To continue, do the following:
- Do as instructed and sign in with Google; Choose an account to continue to Google OAuth 2.0 Playground. Remember to use chuckday402@gmail.com
- Press the button [Allow] to allow Playground to access your Google test account chuckday402@gmail.com.
- Carry out Playground Step 2 and press the button “ Exchange authorization code for tokens”
- Do the following steps to carry out Playground Step 3.
- Press the button “List possible operations”.
- Select the item “Create documents”.
- Press the button “Send the request”.
Switch to the tab “My Drive — Google Drive” then refresh to see a new document was created in Chuck’s drive.
M | A Simple .NET Console Application
This article here provides a complete sequence of the steps to create a simple .NET console application that makes requests to the Drive API. | Tell me more
- Client-ID for Chuck: 1050525399669–7sq71d4eglrfc0dgi1s997u5abj2dbur.apps.googleusercontent.com
- Client Secret: ZkSiuTEJIpbxX2EV4ADAMI3c
N | Google API Client Libraries
Most Google services have web APIs that .NET developers can use to give their applications access to this information with the user’s authorization. | Tell me more
To get started with the .NET client library, find the API you want to use and click the desired version number as found on this page here.
P | Calling .NET Methods from Excel VBA
This page here shows how to call .NET methods from Excel VBA.
X | Pending Information
The following information is necessary for completion of this article.
All applications follow a basic pattern when accessing a Google API using OAuth 2.0. At a high level, you follow four basic steps as spelled out on this page here.
Every request your application sends to the Drive API must include an authorization token. The token also identifies your application to Google. | Tell me more
Источник
Отправка данных из *.XLSX в Google Sheets
Всем привет! Я обычный пользователь MS Excel и Google Docs, любитель-программист на VBA, App Script и JavaScript.
Задача
В данной статье хочу показать как можно быстро и легко отправить объемные данные из файла *.XLSX в Google Sheets при помощи VBA и App Script сохранив тем самым формат отправляемых данных(границы, заливки и прочее).
Цель статьи — поделиться доступным инструментом по отправки данных в Google Sheets из XLSX в автоматическом режиме, при помощи VBA и App Script.
Все инструменты реализованы стандартными средствами VBA, App Script без использования дополнительных библиотек.
Подготовительный этап, в наличии имеем:
Microsoft Excel
Почтавая служба Outlook
Почта Gmail
Практическая часть:
Алгоритм работы автоматической отправки данных с XLSX в Google Sheets заключается в следующем, при помощи VBA отправляем данные через почтовую службу Outlook на свою почту Gmail с определенной меткой, после чего App Script извлекает данные в Google Sheets документ.
В редактроре VBA создадим функцию и процедуру по отправки письма с вложением:
Далее, необходимо в редакторе App Script вашей Google таблицы создать две фукции.Первая, будет проверять входящие письма с «Вашей меткой». Вторая, по созданию новой книги в Google Drive с полученными данными Эксель, которая скопирует в ваш Google sheet и удалить более ненужную книгу с Google Drive.
Функция для извлечения файла Excel
Настраиваем триггер как вам удобно: раз в минуты, каждый час и т.д.
Создаем в Gmail папку с меткой(Label) по которой App Script будет анализировать.На этом этапе завершается механизм получение и обработки данных.
Далее, можно запустить процедуру на VBA «Sub sendMail()» для проверки работоспособнисти механизма и использовать по своего целевому назначению.
Заключение
Реализуемый функционал взаимодействия Эксель с Google Sheets, по отправки и получения данных удобен и практичен как в его реализации так и в обработки значительных объемных данных.
Источник
Google Places Details to Excel with VBA
I’m trying to get a full detail list of Google places to an Excel sheet by using a Text Search request to Google.
So I want to perform an API query (?) by
writing a search string to an Excel cell
getting the VBA to query Google «Place Search» and returning a temporary list of Placeid’s matching the search string
getting the VBA to query all the details of the previous step’s Placeid’s with Google «Place Details» and writing them to the sheet
So the code should «chain» these two APIs to my understanding. I have an API key already for Google.
2 Answers 2
Ok, so some initial work see (BigTest() and EvenBiggerTest()) see remains from prior edit but after re-reading your comments I can see you wanted TextSearch. See please run TestTestSearch()
I have made it multipage aware in that Google returns 20 rows at a time plus a next page token if there is some more; so one supply the next page token to get the next page. This is not working reliably and I do not know why, for London restaurants never more than 60.
Feel free to step through the code, I have made plenty of interim variable which you can observe in the Locals Window to see the JSON structure.
There is some nice VBA.CallbyName logic which few people know about regarding interrogating a JSON structure (I found it on Korean website). Itching to post it on Stackoverflow.
You’ll need to add the following project references, they import libraries
Источник