ahstax
Goto Top

QR-Code aus Internet in Word-Dokument einsetzen

Hallo miteinander,

ich habe hier: http://www.vbaexpress.com/forum/showthread.php?56645-QR-Code-in-Word-20 ... einen funktionierenden VBA-Code gefunden, mit dem man QR-Codes in Word-Dokumenten einsetzen kann. Als Quelle des Codes wird https://chart.apis.google.com/ verwendet, das aber wohl "veraltet" ist (https://developers.google.com/chart/infographics/docs/qr_codes).

Da ich befürchte, dass etwas veraltetes auch abgeschaltet wird, habe ich den Code wie folgt geändert, um als Quelle des QR-Codes http://goqr.me/api/ zu verwenden.

Sub QR_Code_01_goqr_me()
    Dim TMRange As Range
    With ActiveDocument
        Set TMRange = .Bookmarks("Textmarke01").Range  
        URL_QRCode_SERIES_goqr_me "12345678", TMRange  
    End With
End Sub

Function URL_QRCode_SERIES_goqr_me( _
         ByVal QR_Value As String, _
         oRng As Range, _
         Optional ByVal PictureSize As Long = 150, _
         Optional ByVal Updateable As Boolean = True) As Variant

Dim oPic As InlineShape
Dim vLeft As Variant, vTop As Variant
Dim sURL As String

    'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=Example  
Const sRootURL As String = "http://api.qrserver.com/v1/create-qr-code/?"  
Const sSizeParameter As String = "size="  
Const sDataParameter As String = "data="  
Const sMarginParameter As String = "margin=20"  
Const sFormatParameter As String = "format=gif"  
Const sJoinCHR As String = "&"  

    If Updateable = False Then
        URL_QRCode_SERIES_goqr_me = "outdated"  
        GoTo lbl_Exit
    End If

    If Len(QR_Value) = 0 Then
        GoTo lbl_Exit
    End If
    
    sURL = sRootURL & _
            sSizeParameter & PictureSize & "x" & PictureSize & _  
            sJoinCHR & _
            sFormatParameter & _
            sJoinCHR & _
            sMarginParameter & _
            sJoinCHR & _
            sDataParameter & UTF8_URL_Encode(VBA.Replace(QR_Value, " ", "+"))  
          
    MsgBox (sURL)
    
    Set oPic = ActiveDocument.InlineShapes.AddPicture(sURL, False, True, oRng)
lbl_Exit:
    Exit Function
End Function


Function UTF8_URL_Encode(ByVal sStr As String)
'http://www.nonhostile.com/howto-convert-byte-array-utf8-string-vb6.asp (link no longer valid)  
Dim i As Long
Dim a As Long
Dim res As String
Dim code As String

    res = ""  
    For i = 1 To Len(sStr)
        a = AscW(Mid(sStr, i, 1))
        If a < 128 Then
            code = Mid(sStr, i, 1)
        ElseIf ((a > 127) And (a < 2048)) Then
            code = URLEncodeByte(((a \ 64) Or 192))
            code = code & URLEncodeByte(((a And 63) Or 128))
        Else
            code = URLEncodeByte(((a \ 144) Or 234))
            code = code & URLEncodeByte((((a \ 64) And 63) Or 128))
            code = code & URLEncodeByte(((a And 63) Or 128))
        End If
        res = res & code
    Next i
    UTF8_URL_Encode = res
lbl_Exit:
Exit Function
End Function

Private Function URLEncodeByte(val As Integer) As String
Dim res As String
    res = "%" & Right("0" & Hex(val), 2)  
    URLEncodeByte = res
lbl_Exit:
    Exit Function
End Function


Zu meinem Bedauern erhalte ich aber bei dieser Codezeile

Set oPic = ActiveDocument.InlineShapes.AddPicture(sURL, False, True, oRng)

der Funktion "URL_QRCode_SERIES_goqr_me" die Fehlermeldung:

--
Microsoft Visual Basic for Applications
--
Laufzeitfehler '5152':

Dies ist kein gültiger Dateiname.
Versuchen Sie die folgenden Optionen aus:
  • Überprüfen Sie die Pfadangabe.
  • Wählen Sie eine Datei aus der Liste der Dateien und Ordner
--


Die vom Code erzeugte URL lautet http://api.qrserver.com/v1/create-qr-code/?size=150x150&format=gif& ..., die grundsätzlich funktioniert, wenn man sie in einen Browser eingibt.

Das Gegenstück von Google ist https://chart.apis.google.com/chart?chs=150x150&cht=qr&chl=12345 ...

Kann mir jemand sagen, warum der Fehler kommt und was ich ändern muss, damit das funktioniert?

Neugierige Grüße,
Andreas

Content-Key: 488962

Url: https://administrator.de/contentid/488962

Printed on: April 18, 2024 at 08:04 o'clock

Member: godlie
godlie Aug 27, 2019 at 11:36:37 (UTC)
Goto Top
Hallo,

Setz dir mal einen Haltepunkt vor die Funktion und schau mal was in sURL drinnesteht
Member: ahstax
ahstax Aug 27, 2019 at 11:39:55 (UTC)
Goto Top
Mitglied: 140913
140913 Aug 27, 2019 updated at 12:28:22 (UTC)
Goto Top
Hmm du fügst eine URL anstatt einem lokalen Pfad in den Parameter von AddPicture ein, sehr wahrscheinlich ist das der Fehler, oder das Format wird einfach nicht unterstützt.
Lade das Bild also bspw. Über ein XMLHttpObject herunter und nutze dann den lokalen Pfad zum Einfügen in der AddPicture Methode.
Member: godlie
Solution godlie Aug 27, 2019 updated at 13:07:35 (UTC)
Goto Top
Ich gehe mal schwar davon aus, dass die Methode nicht mit einer URL umgehen kann,
dann musst du dir einfach das QR Bild in einen Temp Ordner sichern.

Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _  
    Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _  
    ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Sub download_HK_picture(ByVal url as String)
imgsrc = url
dlpath = "C:\TEMP\"  
URLDownloadToFile 0, imgsrc, dlpath & "QR.gif", 0, 0  
End Sub

Da du ja den 3ten Parameter bei AddPicture auf True gesetzt hast, wird dann beim Speichern das Bild auch ins Dokument eingebunden.
Member: ahstax
ahstax Aug 27, 2019 at 13:22:55 (UTC)
Goto Top
Ich teste das gerne!

Allerdings:
in dem Code, von dem ich ausgegangen bin, wird diese URL:
https://chart.apis.google.com/chart?chs=150x150&cht=qr&chl=12345 ...
erzeugt, die problemlos funktioniert...
Mitglied: 140913
140913 Aug 27, 2019 updated at 13:34:44 (UTC)
Goto Top
Das resultierende Bild aber ein anderes Format (png statt gif), vermutlich macht das den Unterschied, teste einfach mal mit anderem Format (URL-Parameter)
Member: wiesi200
wiesi200 Aug 27, 2019 at 14:11:25 (UTC)
Goto Top
Hallo,

warum verwendest du eigentlich nicht die in Word eingebaute Funktion für QR Codes?
https://support.office.com/de-de/article/hinzuf%C3%BCgen-von-barcodes-zu ...
Member: ahstax
ahstax Aug 27, 2019 at 14:15:39 (UTC)
Goto Top
Weil die leider erst ab Office 2013 verfügbar ist.
Member: ahstax
ahstax Aug 27, 2019 at 14:29:08 (UTC)
Goto Top
Zitat von @godlie:

Ich gehe mal schwar davon aus, dass die Methode nicht mit einer URL umgehen kann,
dann musst du dir einfach das QR Bild in einen Temp Ordner sichern.

Ja, das scheint des Rätsels Lösung zu sein. Wenn ich den Umweg über den Download gehe, dann klappts. Man muss nur dafür sorgen, dass der Download-Ordner vorhanden ist...
Member: monstermania
monstermania Aug 27, 2019 at 14:43:43 (UTC)
Goto Top
Moin,
nur mal so als Tip.
Ich würde gleich auf ein Barcode-Tool wie Zint setzen. https://sourceforge.net/projects/zint/
Dann brauchst Du Dir wegen erforderlicher Online-Verbindung und evtl. API-Änderungen keine Gedanken zu machen!

Außerdem ist so etwas auch universell einsetzbar, da Zint quasi alle gängien BC-Typen unterstützt.

Gruß
Dirk
Member: godlie
godlie Aug 27, 2019 at 15:34:21 (UTC)
Goto Top
Sehr schön, ja ohne Ordner hauts ihn natürlich auf die Fresse face-smile

Setz doch noch den Thread auf gelöst und markiere den Lösungsthread.

grüße
Member: ahstax
ahstax Aug 28, 2019 at 12:03:57 (UTC)
Goto Top
Herzlichen Dank allen für die Hilfe!

Hier noch die jetzt bei mir für meine Belange funktionierende Lösung für ein Dokument, in dem die Textmarke "Textmarke01" vorhanden ist:

Option Explicit

Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _  
    Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _  
    ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Sub QR_Code_01_goqr_me()
On Error GoTo Errorhandler

Dim bolError As Boolean
bolError = False

Dim TMRange As Range

    With ActiveDocument
        Set TMRange = .Bookmarks("Textmarke01").Range  
        URL_QRCode_SERIES_goqr_me "P-12345-DE-1", TMRange  
        If Fkt_GetAndSet_QR_Codes("P-12345-DE-1", TMRange) = False Then  
           bolError = True
        End If
    End With
    
    ActiveDocument.Saved = True
        
    Dim result As VbMsgBoxResult
    If bolError = True Then
        result = MsgBox("Beim Abrufen und/oder EInfügen eines QR-Codes trat ein Fehler auf." & vbCrLf & _  
        "Das Dokument wird geschlossen", vbOKOnly, "Fehler --> Abbruch")  
        GoTo Errorhandler
    End If

    Exit Sub

Errorhandler:

    ActiveDocument.Saved = True
    Application.Quit SaveChanges:=wdDoNotSaveChanges

End Sub

Function Fkt_GetAndSet_QR_Codes(ByVal strTextmarke As String, ByVal strQRInhalt As String) As Boolean
    
    Fkt_GetAndSet_QR_Codes = True
    
    Dim TMRange As Range
    
    On Error GoTo ErrHandling
    
    With ActiveDocument
        If .Bookmarks.Exists(strTextmarke) Then
            Set TMRange = .Bookmarks(strTextmarke).Range
                         
            'yy_URL_QRCode_SERIES strQRInhalt, TMRange  
            If URL_QRCode_SERIES_goqr_me(strQRInhalt, TMRange) = False Then
                GoTo ErrHandling
            End If
                 
            .Bookmarks.Add strTextmarke, TMRange
            Fkt_GetAndSet_QR_Codes = True
        End If
    End With

Exit Function

ErrHandling:
    Fkt_GetAndSet_QR_Codes = False

End Function


Function URL_QRCode_SERIES_goqr_me( _
         ByVal QR_Value As String, _
         oRng As Range, _
         Optional ByVal PictureSize As Long = 150, _
         Optional ByVal Updateable As Boolean = True) As Boolean


URL_QRCode_SERIES_goqr_me = False
On Error GoTo lbl_Exit


Dim oPic As InlineShape
Dim vLeft As Variant, vTop As Variant
Dim sURL As String

    'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=Example  
Const sRootURL As String = "http://api.qrserver.com/v1/create-qr-code/?"  
Const sSizeParameter As String = "size="  
Const sDataParameter As String = "data="  
Const sMarginParameter As String = "margin=20"  
Const sFormatParameter1 As String = "format="  
Const sFormatParameter2 As String = "gif"  
Const sJoinCHR As String = "&"  

    If Updateable = False Then
        URL_QRCode_SERIES_goqr_me = "outdated"  
        GoTo lbl_Exit
    End If

    If Len(QR_Value) = 0 Then
        GoTo lbl_Exit
    End If
    
    sURL = sRootURL & _
            sSizeParameter & PictureSize & "x" & PictureSize & _  
            sJoinCHR & _
            sMarginParameter & _
            sJoinCHR & _
            sFormatParameter1 & sFormatParameter2 & _
            sJoinCHR & _
            sDataParameter & UTF8_URL_Encode(VBA.Replace(QR_Value, " ", "+"))  
          
    'MsgBox (sURL)  
    
        
    Dim pfad_T1 As String
    pfad_T1 = "C:\temp\QR\"  
    Dim pfad_T2 As String
    pfad_T2 = QR_Value & "." & sFormatParameter2  
    Dim pfad As String
    pfad = pfad_T1 & pfad_T2
    
    If Dir(pfad_T1, vbDirectory) = "" Then  
        'directory doesn't exist  
        MkDir Path:=pfad_T1
    Else
        'directory does exist  
    End If

    
    If GURoL(sURL, pfad) = True Then
        Set oPic = ActiveDocument.InlineShapes.AddPicture(pfad, False, True, oRng)
        URL_QRCode_SERIES_goqr_me = True
    Else
        'MsgBox ("MIST...!")  
        URL_QRCode_SERIES_goqr_me = False
    End If

    Exit Function

lbl_Exit:
    URL_QRCode_SERIES_goqr_me = False
    Exit Function
End Function


Public Function GURoL(url As String, FileName As String) As Boolean
    GURoL = False
    Dim lngRetVal As Long
    lngRetVal = URLDownloadToFile(0, url, FileName, 0, 0)
    If lngRetVal <> 0 Then
        'MsgBox "GURol godo: Can't download from " & url & " to " & FileName  
        GURoL = False
    Else
        GURoL = True
    End If
End Function

Function UTF8_URL_Encode(ByVal sStr As String)
'http://www.nonhostile.com/howto-convert-byte-array-utf8-string-vb6.asp (link no longer valid)  
Dim i As Long
Dim a As Long
Dim res As String
Dim code As String

    res = ""  
    For i = 1 To Len(sStr)
        a = AscW(Mid(sStr, i, 1))
        If a < 128 Then
            code = Mid(sStr, i, 1)
        ElseIf ((a > 127) And (a < 2048)) Then
            code = URLEncodeByte(((a \ 64) Or 192))
            code = code & URLEncodeByte(((a And 63) Or 128))
        Else
            code = URLEncodeByte(((a \ 144) Or 234))
            code = code & URLEncodeByte((((a \ 64) And 63) Or 128))
            code = code & URLEncodeByte(((a And 63) Or 128))
        End If
        res = res & code
    Next i
    UTF8_URL_Encode = res
lbl_Exit:
Exit Function
End Function

Private Function URLEncodeByte(val As Integer) As String
Dim res As String
    res = "%" & Right("0" & Hex(val), 2)  
    URLEncodeByte = res
lbl_Exit:
    Exit Function
End Function


Sonnige Grüße,
Andreas