我正在使用 VBA Access 從 Google Books 獲取圖書館資料庫的資料。該代碼基于this stackoverflow question中給出的代碼。
由于資訊位于嵌套陣列中,我正在努力尋找正確的代碼以允許不同數量的作者。我希望所有作者姓名都出現在一個文本框中。
我試過了:
Form_AddAmendItems.AuthorTextBox.Value = Join(subitem("authors"), ",")
從上面的鏈接,但未能找到任何結果。
我想我需要使用 UBound 和 LBound 來計算作者的數量,然后回圈并添加每個作者。但我還沒有找到如何做到這一點的例子。
目前,作為一種解決方法,我可以使用最多 3 位作者的姓名填充 AuthorTextBox,這足以滿足我的需要。但如果作者少于 3 位,則會彈出錯誤處理程式訊息,因為它無法找到請求的資料。
我正在使用這里的 VBA-JSON 轉換器。
這是我想決議的 JSON(從這里)
{
"kind": "books#volumes",
"totalItems": 1,
"items": [
{
"kind": "books#volume",
"id": "BT2CAz-EjvcC",
"etag": "6Z7JqyUtyJU",
"selfLink": "https://www.googleapis.com/books/v1/volumes/BT2CAz-EjvcC",
"volumeInfo": {
"title": "Collins Gem German Dictionary",
"subtitle": "German-English, English-German",
"authors": [
"Veronika Calderwood-Schnorr",
"Ute Nicol",
"Peter Terrell"
]
這是我的 VBA 代碼:
Private Sub FindBookDetailsButton_Click()
'Error handle for Null Strings
If IsNull(Me.ISBNTextBox) = True Then
MsgBox "Item ID not specified.", vbExclamation vbOKOnly, "Error"
Exit Sub
End If
'Error message if there is no match
On Error GoTo ErrMsg
Dim http As Object, JSON As Object, i As Integer, subitem As Object
Dim ISBN As String
ISBN = CStr(Me.ISBNTextBox.Value)
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://www.googleapis.com/books/v1/volumes?q=isbn:" & ISBN, False
http.send
Set JSON = ParseJSON(http.responseText)
For Each item In JSON("items")
Set subitem = item("volumeInfo")
Form_AddAmendItems.TitleTextBox.Value = subitem("title")
Form_AddAmendItems.AuthorTextBox.Value = subitem("authors")(1)
Form_AddAmendItems.PublisherTextBox.Value = subitem("publisher")
'For multiple authors
Set subitem = item("volumeInfo")
If subitem.Exists("authors") Then
For Each item2 In subitem("authors")
Form_AddAmendItems.AuthorTextBox.Value = subitem("authors")(1) & ", " & subitem("authors")(2)
Next
For Each item3 In subitem("authors")
Form_AddAmendItems.AuthorTextBox.Value = subitem("authors")(1) & ", " & subitem("authors")(2) & ", " & subitem("authors")(3)
Next
End If
Next
'To end with success
MsgBox ("Process complete"), vbInformation
Exit Sub
'To end with an error message
ErrMsg:
MsgBox ("No match obtained"), vbCritical
End Sub
uj5u.com熱心網友回復:
可以在不知道物件限制的情況下回圈陣列、集合或字典。因此,如果subitem("authors")
是其中一種物件型別,您的代碼可能類似于(基本上是您問題中 SO 鏈接的接受答案中顯示的代碼):
Set subitem = item("volumeInfo")
Form_AddAmendItems.TitleTextBox.Value = subitem("title")
Form_AddAmendItems.PublisherTextBox.Value = subitem("publisher")
If subitem.Exists("authors") Then
For Each item2 In subitem("authors")
sA = sA & item2 & ","
Next
sA = Left(sA, Len(sA) - 1) 'remove trailing comma
If sA <> "" Then Form_AddAmendItems.AuthorTextBox.Value = sA
End If
我發現 ISBN 下載中的元素并不總是相同的。例如,對于 ISBN 0-575-05577-4,即使提供了發布日期,也沒有提供發布者。可以為您要顯式處理的每個元素使用 If Then 條件。附帶說明一下,有趣的是,這本書的合著者沒有被包括在內。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/508018.html
上一篇:使用自動編號訪問添加記錄問題