Домашняя страница Undo Do New Save Карта сайта Обратная связь Поиск по форуму
МИР MS EXCEL - Гость.xls

Вход

Регистрация

Напомнить пароль

 

= Мир MS Excel/Заполнить google sheets данными из excel, при помощи vba - Страница 2 - Мир MS Excel

Старая форма входа
  • Страница 2 из 2
  • «
  • 1
  • 2
Модератор форума: _Boroda_, китин  
Мир MS Excel » Вопросы и решения » Excel и другие приложения » Google Docs » Заполнить google sheets данными из excel, при помощи vba
Заполнить google sheets данными из excel, при помощи vba
airatgimranoff Дата: Вторник, 13.06.2023, 18:52 | Сообщение № 21
Группа: Пользователи
Ранг: Прохожий
Сообщений: 1
Репутация: 0 ±
Замечаний: 0% ±

2021
TvoiExcel,
VBA часть:
[vba]
Код
Sub sendPOST()

Const webAppId As String = "********" 'Id веб-приложения, доступного всем после авторизации

Dim httpRequest As Object 'MSXML2.XMLHTTP
Dim URL As String
Dim requestBody As Variant
Dim row As Integer, col As Integer

Dim rng As Range
Set rng = ActiveSheet.Range(Cells(1, 1), Cells(23, 14)) 'выбираем любой диапазон на активном листе

Dim content as String
content = ToArrJSON(rng)

requestBody = "&content=" & EncodeUriComponent(content)

URL = "https://script.google.com/macros/s/" & webAppId & "/exec"

Set httpRequest = CreateObject("MSXML2.XMLHTTP")
httpRequest.Open "POST", URL, False
httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpRequest.Send requestBody

Set httpRequest = Nothing

End Sub
[/vba]

[vba]
Код
'конвертируем Кириллицу
Public Function EncodeUriComponent(str)
Static objHtmlfile As Object
If objHtmlfile Is Nothing Then
Set objHtmlfile = CreateObject("htmlfile")
objHtmlfile.parentWindow.execScript "function encode(s) {return encodeURIComponent(s)}", "jscript"
End If
EncodeUriComponent = objHtmlfile.parentWindow.encode(str)
End Function
[/vba]

[vba]
Код
'заворачиваем данные из диапазона rng в JSON
Public Function ToArrJSON(rng As Range) As String
' Make sure there are two columns in the range
If rng.Columns.Count < 2 Then
ToArrJSON = CVErr(xlErrNA)
Exit Function
End If

Dim dataLoop, headerLoop As Long
' Get the first row of the range as a header range
Dim headerRange As Range: Set headerRange = Range(rng.Rows(1).Address)

Dim colCount As Long: colCount = headerRange.Columns.Count

Dim json As String: json = "["

For dataLoop = 0 To rng.Rows.Count
' Include the first header row as well
If dataLoop > 0 Then
' Start data row
Dim rowJson As String: rowJson = "["

For headerLoop = 1 To colCount
rowJson = rowJson & """" & rng.Value2(dataLoop, headerLoop) & """"
rowJson = rowJson & ","
Next headerLoop

' Strip out the last comma
rowJson = Left(rowJson, Len(rowJson) - 1)

' End data row
json = json & rowJson & "],"
End If
Next

' Strip out the last comma
json = Left(json, Len(json) - 1)

json = json & "]"

ToArrJSON = json
End Function
[/vba]

Google Script часть:

[vba]
Код
function doPost(e) {

let ss = SpreadsheetApp.openById('************'); //id файла
let sheet = ss.getSheetByName('*******');//имя листа

let content = e.parameter.content;
let parsedContent = JSON.parse(content);
let ResultArray = [parsedContent[0].slice()];

for (let i=1; i<parsedContent.length; i++) {
ResultArray.push( parsedContent[i].slice() )
}

let needRows = ResultArray.length;
let needCols = ResultArray[0].length;

sheet.getRange(1, 1, needRows, needCols).setValues(ResultArray)
}
[/vba]

Сохраняем. Делаем развёртывание. У меня всё работает. Присваиваем в VBA переменной webAppId нужный адрес Вэб-Приложения (после развёртывания копируем с экрана) .

В прикреплённом скрине все подключения, которые у меня есть в Tools => References =>
К сообщению приложен файл: 4872605.png (123.0 Kb)


Сообщение отредактировал Serge_007 - Среда, 14.06.2023, 09:34
 
Ответить
СообщениеTvoiExcel,
VBA часть:
[vba]
Код
Sub sendPOST()

Const webAppId As String = "********" 'Id веб-приложения, доступного всем после авторизации

Dim httpRequest As Object 'MSXML2.XMLHTTP
Dim URL As String
Dim requestBody As Variant
Dim row As Integer, col As Integer

Dim rng As Range
Set rng = ActiveSheet.Range(Cells(1, 1), Cells(23, 14)) 'выбираем любой диапазон на активном листе

Dim content as String
content = ToArrJSON(rng)

requestBody = "&content=" & EncodeUriComponent(content)

URL = "https://script.google.com/macros/s/" & webAppId & "/exec"

Set httpRequest = CreateObject("MSXML2.XMLHTTP")
httpRequest.Open "POST", URL, False
httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpRequest.Send requestBody

Set httpRequest = Nothing

End Sub
[/vba]

[vba]
Код
'конвертируем Кириллицу
Public Function EncodeUriComponent(str)
Static objHtmlfile As Object
If objHtmlfile Is Nothing Then
Set objHtmlfile = CreateObject("htmlfile")
objHtmlfile.parentWindow.execScript "function encode(s) {return encodeURIComponent(s)}", "jscript"
End If
EncodeUriComponent = objHtmlfile.parentWindow.encode(str)
End Function
[/vba]

[vba]
Код
'заворачиваем данные из диапазона rng в JSON
Public Function ToArrJSON(rng As Range) As String
' Make sure there are two columns in the range
If rng.Columns.Count < 2 Then
ToArrJSON = CVErr(xlErrNA)
Exit Function
End If

Dim dataLoop, headerLoop As Long
' Get the first row of the range as a header range
Dim headerRange As Range: Set headerRange = Range(rng.Rows(1).Address)

Dim colCount As Long: colCount = headerRange.Columns.Count

Dim json As String: json = "["

For dataLoop = 0 To rng.Rows.Count
' Include the first header row as well
If dataLoop > 0 Then
' Start data row
Dim rowJson As String: rowJson = "["

For headerLoop = 1 To colCount
rowJson = rowJson & """" & rng.Value2(dataLoop, headerLoop) & """"
rowJson = rowJson & ","
Next headerLoop

' Strip out the last comma
rowJson = Left(rowJson, Len(rowJson) - 1)

' End data row
json = json & rowJson & "],"
End If
Next

' Strip out the last comma
json = Left(json, Len(json) - 1)

json = json & "]"

ToArrJSON = json
End Function
[/vba]

Google Script часть:

[vba]
Код
function doPost(e) {

let ss = SpreadsheetApp.openById('************'); //id файла
let sheet = ss.getSheetByName('*******');//имя листа

let content = e.parameter.content;
let parsedContent = JSON.parse(content);
let ResultArray = [parsedContent[0].slice()];

for (let i=1; i<parsedContent.length; i++) {
ResultArray.push( parsedContent[i].slice() )
}

let needRows = ResultArray.length;
let needCols = ResultArray[0].length;

sheet.getRange(1, 1, needRows, needCols).setValues(ResultArray)
}
[/vba]

Сохраняем. Делаем развёртывание. У меня всё работает. Присваиваем в VBA переменной webAppId нужный адрес Вэб-Приложения (после развёртывания копируем с экрана) .

В прикреплённом скрине все подключения, которые у меня есть в Tools => References =>

Автор - airatgimranoff
Дата добавления - 13.06.2023 в 18:52
Мир MS Excel » Вопросы и решения » Excel и другие приложения » Google Docs » Заполнить google sheets данными из excel, при помощи vba
  • Страница 2 из 2
  • «
  • 1
  • 2
Поиск:

Яндекс.Метрика Яндекс цитирования
© 2010-2024 · Дизайн: MichaelCH · Хостинг от uCoz · При использовании материалов сайта, ссылка на www.excelworld.ru обязательна!