Calling a Vba script in a HTML5 page - html

I create a script in Vba allowing to compare reports in Word and I would like to create a page in HTML allowing to launch the Vba script after clicking a button.
When I try to do that, I obtain the message "ReferenceError: myFunction is not defined" in Firefox and Chrome. If I try the same on IE, I obtain the error "'myFunction' is undefined".
<!DOCTYPE html>
<html>
<head>
<title>Reports Comparison</title>
<script type="text/vbscript" src="myScript.vbs"></script>
</head>
<body>
<input type="button" value="Test" onClick="myFunction()">
</body>
</html>
myFunction is correctly defined in the file myScript.vbs :
Sub myFunction ()
Dim strFolderA As String
Dim strFolderB As String
Dim strFolderC As String
Dim strFileSpec As String
Dim strFileName As String
Dim objDocA As Word.Document
Dim objDocB As Word.Document
Dim objDocC As Word.Document
strFolderA = InputBox("Enter path to base documents:")
strFolderB = InputBox("Enter path to new documents:")
strFolderC = InputBox("Enter path for document comparisons to be saved:")
strFileSpec = "*.docx"
strFileName = Dir(strFolderA & strFileSpec)
Do While strFileName <> vbNullString
Set objDocA = Documents.Open(strFolderA & strFileName)
Set objDocB = Documents.Open(strFolderB & strFileName)
Application.CompareDocuments _
OriginalDocument:=objDocA, _
RevisedDocument:=objDocB, _
Destination:=wdCompareDestinationNew
objDocA.Close
objDocB.Close
Set objDocC = ActiveDocument
objDocC.SaveAs FileName:=strFolderC & strFileName
objDocC.Close SaveChanges:=False
strFileName = Dir
Loop
Set objDocA = Nothing
Set objDocB = Nothing
End Sub
Could you please help me to do that?
Regards

VBScript can only be used in Internet Explorer. And even then it won't work by default, you have to enable "Enterprise Mode" to enable backwards compatibility and various other flags to allow the browser access to the file system. You also can't work with a Word document like this without some extra legwork since Word won't be defined here.
There is a new Javascript API that you might be able to leverage instead but again this isn't for use in the context of a browser. But it would let you add some functionality to word itself.
https://dev.office.com/reference/add-ins/javascript-api-for-office

Related

Convert RTF embedded OLE to HTML in Access in VBA

I've got a table that has an embedded OLE field that contains RichText formatted data. I need to transfer this data to MySQL database and convert it to HTML. I use Access. Is there a way to do it quickly in VBA?
I searched the web, most people use RichText control (richtx32.ocx) to get plain text, but I need it to remain formatted and I also don't have this control.
Here is how I solved my problem:
Option Explicit
Public wrd As Word.Application
Public doc As Word.Document
Function RTF2HTMLviaWord(rtf As String) As String
'Open Tools --> References --> and check Microsoft Scripting Runtime
Dim fso As New FileSystemObject
Dim text As TextStream
Dim temp As String
temp = Environ("TEMP")
If Len(rtf) > 1 Then
Set text = fso.CreateTextFile(temp & "\RTF2HTML.rtf", True)
text.Write rtf
text.Close
If wrd Is Nothing Then
Set wrd = New Word.Application
End If
Set doc = wrd.Documents.Open(temp & "\RTF2HTML.rtf", False)
doc.SaveAs temp & "\RTF2HTML.htm", wdFormatHTML
doc.Close
fso.DeleteFile temp & "\RTF2HTML.rtf"
Set text = fso.OpenTextFile(temp & "\RTF2HTML.htm", ForReading, False)
RTF2HTMLviaWord = text.ReadAll
text.Close
fso.DeleteFile temp & "\RTF2HTML.htm"
Else
RTF2HTMLviaWord = ""
End If
End Function
The only downside is that Word produces too many garbage HTML tags. I wish it could save minimal HTML tags without formatting.

How can I retrieve Amazon's keyword/phrase suggestions from the search bar

Below is some code I've found and altered to attempt to capture the keyword/phrase suggestions from Amazon's search bar. I'm very new to the concept of web scraping, so I know the code presented here may be very ineffective and inefficient. I've manually captured some data from the F12 DOM Explorer and Network windows. If the best answer is web scraping, I need that in the form of excel vba. I see in some of the below images that it appears as though some of the content type from the Network window is "application/json" and the Initiator/Type is "XMLHttpRequest", but this is only after it shows a connection and authentication to "https://completion.amazon.com". If that's the route, I have no idea how to complete those requests. Any help would be much appreciated.
So far I've tried invoking the search bar programmatically, via the scripts in the code, but that does nothing that I can see. Simply 'pasting' the keyword into the search bar with a 'space' appended to it does not produce the suggested keywords. However, typing into the search bar does. If I type the keyword in, then choose 'inspect element' of the dropdown suggestions, dynamic HTML is produced to show the HTML content of the suggestions (at which time I can get what I need). I've been unsuccessful in getting to that point.
Private Sub CommandButton1_Click()
Dim MyHTML_Element As IHTMLElement
Dim MyURL As String
Dim AASearchRank As Workbook
Dim AAws As Worksheet
Dim InputSearch As HTMLInputTextElement
Dim elems As IHTMLElementCollection
Dim TDelement As HTMLTableCell
Dim elems2 As IHTMLElementCollection
Dim TDelement2 As HTMLDivElement
'Dim TDelement2 As HTMLInputTextElement
Dim InputSearchButton As HTMLInputButtonElement
Dim IE As InternetExplorer
Dim x As Integer
Dim i As Long
MyURL = "https://www.amazon.com/"
Set IE = New InternetExplorer
With IE
.Silent = True
.Navigate MyURL
.Visible = True
Do
DoEvents
Loop Until .ReadyState = READYSTATE_COMPLETE
End With
Set HTMLDoc = IE.Document
Set AASearchRank = Application.ThisWorkbook
Set AAws = AASearchRank.Worksheets("Sheet2")
Set InputSearchButton = HTMLDoc.getElementById("nav-search-submit-text")
Set InputSearchOrder = HTMLDoc.getElementById("twotabsearchtextbox")
If Not InputSearchOrder Is Nothing Then
InputSearchButton.Click
Do
DoEvents
Loop Until IE.ReadyState = READYSTATE_COMPLETE
End If
x = 2
If AAws.Range("D" & x).Value = "" Then
Do Until AAws.Range("B" & x) = ""
Set InputSearch = HTMLDoc.getElementById("twotabsearchtextbox")
InputSearch.Focus
'When a keyword is typed in the search bar with a 'space' after, it invokes the suggestions I'm looking for.
InputSearch.Value = "Travel "
'InputSearch.Value = AAws.Range("C" & x) & " "
Set InputSearchButton = HTMLDoc.getElementsByClassName("nav-input")(0)
InputSearch.Focus
'Here I was trying to invoke some script to see if it had any effect on the search bar drop down
HTMLDoc.parentWindow.execScript "window.navmet.push({key:'UpNav',end:+new Date(),begin:window.navmet.tmp});"
HTMLDoc.parentWindow.execScript "window.navmet.push({key:'Search',end:+new Date(),begin:window.navmet.tmp});"
HTMLDoc.parentWindow.execScript "window.navmet.push({key:'NavBar',end:+new Date(),begin:window.navmet.main});"
Do
DoEvents
Loop Until IE.ReadyState = READYSTATE_COMPLETE
'Application.Wait (Now + TimeValue("0:00:05"))
Set elems2 = HTMLDoc.getElementsByClassName("nav-issFlyout nav-flyout")
i = 0
For Each TDelement2 In elems2
'Debug statements strictly for learning what each option/query returns
Debug.Print TDelement2.innerText
Debug.Print TDelement2.className
Debug.Print TDelement2.dataFld
Debug.Print TDelement2.innerHTML
Debug.Print TDelement2.outerText
Debug.Print TDelement2.outerHTML
Debug.Print TDelement2.parentElement.className
Debug.Print TDelement2.tagName
Debug.Print TDelement2.ID
Next
'Once the searchbar is populated, and the drop down list provides suggestions,
'the below code will give me what I want. If there's an easier solution,
'I'm all for it
Set elems = HTMLDoc.getElementsByClassName("s-suggestion")
i = 0
For Each TDelement In elems
If Left(TDelement.ID, 6) = "issDiv" Then
Debug.Print TDelement.innerText
Debug.Print TDelement.ID
End If
Next
x = x + 1
Loop
End If
End Sub
An ideal solution would be to obtain these suggested keywords through either invoking the search bar dynamic HTML or via Amazon's completion site, but it appears as though that might not be open to the general public. Thank you for any help, and apologies up front for any posting deficiencies.
There is an API call you can find in the network tab. It returns a json string you can parse with as jsonparser to get the suggestions. I use jsonconverter.bas which, once downloaded I add to the project and then go VBE > Tools > References > Add a reference to Microsoft Scripting Runtime.
The url itself is a queryString i.e. it is constructed of different parameters. For example, there is a limit parameter, whose value is 11, which specifies the number of suggestions to return. You may be able to alter and/or remove some of these. Below, I concatenate the SEARCH_TERM constant into the query string to represent your search value (that which would be typed into the search box).
I don't know whether any of the params are time-based (i.e. expire over time - I have made a number of requests without problem since you posted your question). It may be that necessary time based values can be pulled via a prior GET request to Amazon search page.
params = (
('session-id', '141-0042012-2829544'),
('customer-id', ''),
('request-id', '7E7YCB7AZZM1HQEZF2G1'),
('page-type', 'Search'),
('lop', 'en_US'),
('site-variant', 'desktop'),
('client-info', 'amazon-search-ui'),
('mid', 'ATVPDKIKX0DER'),
('alias', 'aps'),
('b2b', '0'),
('fresh', '0'),
('ks', '76'),
('prefix', 'TRAVEL'),
('event', 'onKeyPress'),
('limit', '11'),
('fb', '1'),
('suggestion-type', ['KEYWORD', 'WIDGET']),
('_', '1556820864750')
)
VBA:
Option Explicit
Public Sub GetTable()
Dim json As Object, suggestion As Object '< VBE > Tools > References > Microsoft Scripting Runtime
Const SEARCH_TERM As String = "TRAVEL"
Const SEARCH_TERM2 As String = "BOOKS"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://completion.amazon.com/api/2017/suggestions?session-id=141-0042012-2829544" & _
"&customer-id=&request-id=7E7YCB7AZZM1HQEZF2G1&page-type=Search&lop=en_US&site-variant=" & _
"desktop&client-info=amazon-search-ui&mid=ATVPDKIKX0DER&alias=aps&b2b=0&fresh=0&ks=76&" & _
"prefix=" & SEARCH_TERM & "&event=onKeyPress&limit=11&fb=1&suggestion-type=KEYWORD&suggestion-type=" & _
"WIDGET&_=1556820864750", False
.setRequestHeader "User-Agent", "Mozilla/5.0"
.send
Set json = JsonConverter.ParseJson(.responseText)("suggestions")
End With
For Each suggestion In json
Debug.Print suggestion("value")
Next
End Sub

Microsoft access vba-shift focus from access to word

I am creating and opening a word document through access 2007 vba. The document is created but the focus is not shifted to word. Instead the focus still remains on access form through which am creating the doc. Below is my code:
Dim obj As Word.Application
Dim wor As Word.Document
Dim str As String
str = "C:\hello\folder1\vin.dot"
Set obj = CreateObject("Word.Application")
Set wor = obj.Documents.Add
With wor
.SaveAs str
.Close
End With
obj.Visible = True
obj.Documents.Open str
obj.WindowState = wdWindowStateMaximize
Any sugesstions please.
You can move the focus with AppActivate;
AppActivate "Microsoft Word"
The VBA Word.Application object may have more than one Window associated with it. You may specify which Window to display by using its Caption property.
Since you created a new Word.Application and only created one Document, you may assume that the 1st element (1-based array) is what you want to display in your code.
AppActivate (obj.Windows(1).Caption)
I was able to call the specific window even with other word documents open with the following:
Private Sub but_Click()
'must add tools > references Microsoft Word XX.X Object Library (xx.x is max update)
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
strProjPath = Application.CurrentProject.Path 'get current path
strVerWord = "test" 'i use this to identify paths that can change based on network configs.
posOp = InStr(1, strProjPath, strVerWord) ' find the verification word in the path
strVerPath = "strVerWord filepath\FP\FP\document.docx" 'create string location for document
strPathPlusDBName = Left(strProjPath, posOp - 1) & strVerPath
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Open(FileName:=strPathPlusDBName, ReadOnly:=True) 'open word file in read only
AppActivate WordDoc
End Sub

Creating 2D (Data Matrix or QR Codes) in MS Access Reports/Forms

We are in the process of implementing code to read/create 2D bar codes that are starting to show up on our supplier's parts.
We have a need to create the 2D bar codes in MS Access reports and forms. Has anyone had success with the font (IDAutomation) or Active X (dlSoft) solutions out there.
For C#, the open source library "http://barcoderender.codeplex.com/" was suggested. Any thoughts on how successful this was or if anyone has other open-source and/or pay for options.
Thanks,
Anton
Depending on the volume of codes you need to generate, you could use the Google Charts API to generate QR Codes.
Simply add a "Microsoft Web Browser" ActiveX component and the following code to your Form:
Dim Size As Integer
Dim Text As String
Dim URL As String
Size = 200
Text = "This is my test"
' Better to actually use a URL encoding function like those described here:
' http://stackoverflow.com/questions/218181/how-can-i-url-encode-a-string-in-excel-vba
Text = Replace(Text, " ", "%20")
URL = "http://chart.apis.google.com/chart?chs=" & Size & "x" & Size & "&cht=qr&chld=H|0&chl=" & Text
WebBrowser.Navigate (URL)
You can of course change the Size and the Text depending on your need. The Text can also be a value directly from your Form, therefore your data.
I would advise you to check Googles Terms and Services before using it.
I completely escaped the web browser control and the Google API since that functionality is now deprecated from what I can tell. I went with a different free API but the Google API or any other API could be used instead.
In my example I am creating an .png image in the same directory as the application. I have a text box on my form named txtToCode in which I type in any text I want to code. I also have an image control so that the image can be viewed from the form, but you can modify it how you wish:
Private Sub btnCode2_Click()
Call GetQRCode(Me.txtToCode, 150, 150)
End Sub
Sub GetQRCode(Content As String, Width As Integer, Height As Integer)
Dim ByteData() As Byte
Dim XmlHttp As Object
Dim HttpReq As String
Dim ReturnContent As String
Dim EncContent As String
Dim QRImage As String
EncContent = EncodeURL(Content)
HttpReq = "https://api.qrserver.com/v1/create-qr-code/?data=" & EncContent & "&size=" & Width & "x" & Height & ""
Set XmlHttp = CreateObject("MSXML2.XmlHttp")
XmlHttp.Open "GET", HttpReq, False
XmlHttp.Send
ByteData = XmlHttp.responseBody
Set XmlHttp = Nothing
ReturnContent = StrConv(ByteData, vbUnicode)
Call ExportImage(ReturnContent)
End Sub
Private Sub ExportImage(image As String)
Dim FilePath As String
On Error GoTo NoSave
' Build Export Path
FilePath = Application.CurrentProject.Path & "\qr.png"
Open FilePath For Binary As #1
Put #1, 1, image
Close #1
Me.Image3.Picture = FilePath
' Save File Path
Exit Sub
NoSave:
MsgBox "Could not save the QR Code Image! Reason: " & Err.Description, vbCritical, "File Save Error"
End Sub
Private Function EncodeURL(str As String)
Dim ScriptEngine As Object
Dim encoded As String
Dim Temp As String
Temp = Replace(str, " ", "%20")
Temp = Replace(Temp, "#", "%23")
EncodeURL = Temp
End Function

Can I automatically convert .ppt to .html?

I have been trying to work out the best way for a power point to be shown on a Intranet. The users in the company will not be very technical and might not follow the processes I will describe.
I found this page
Which shows how to convert a power point in to a html page which can be viewed. I was wanting to know if there is some way to automate this process. Such as a file watcher watching the location it will saved and then as soon as it is seen automatically changes this to a html using the code provided on the page I gave. Preferred language to use would be VB.NET.
I am happy for any suggestions that people can give.
Thanks in advance
You can try with this code - based on Microsoft.Office.Interop.PowerPoint.Application
You have sample of code in order to try functionality
View Aspx
<%# Page Language="VB" AutoEventWireup="false" CodeFile="AspNetPowerPointConvertToHTML.aspx.vb" Inherits="AspNetPowerPointConvertToHTML" %>
<html>
<head>
<title>ShotDev.Com Tutorial</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label id="lblText" runat="server"></asp:Label>
</form>
</body>
</html>
Code behind
Imports Microsoft.Office.Interop.PowerPoint
Public Class AspNetPowerPointConvertToHTML
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim ppApp As New Microsoft.Office.Interop.PowerPoint.Application
Dim ppName As String = "MySlides.ppt"
Dim FileName As String = "MyPP/MyPPt"
ppApp.Visible = True
ppApp.Presentations.Open(Server.MapPath(ppName))
ppApp.ActivePresentation.SaveAs(Server.MapPath(FileName), 13)
ppApp.Quit()
ppApp = Nothing
Me.lblText.Text = "PowerPoint Created to Folder <strong> " & FileName & "</strong>"
End Sub
End Class
I've used the:
Imports PowerPoint = Microsoft.Office.Interop.PowerPoint
to be able to automatically change a power point in to a HTML. I've used a file watcher to watch a directory on my computer to look out for power point presentations at the moment it is only set to .pptx however I'll change this to add other formats soon. This fileWater is sat on a service that starts up when the computer does. It then looks to see if a powerpoint has been created or modified and runs this code:
Private Shared Sub OnChanged(ByVal source As Object, ByVal e As FileSystemEventArgs)
'set varaibles so that html can save in correct place
Dim destinationDirectory As String = e.FullPath.Replace(e.Name.ToString(), "")
Dim sourceLocation As String
Dim fileName As String
'couple of if statements to get rid of unwanted characters
If e.Name.Contains("~$") Then
fileName = e.Name.Replace("~$", "")
fileName = fileName.Replace(".pptx", ".html")
Else
fileName = e.Name
fileName = fileName.Replace(".pptx", ".html")
End If
If e.FullPath.Contains(("~$")) Then
sourceLocation = e.FullPath.Replace("~$", "")
Else
sourceLocation = e.FullPath
End If
Dim strSourceFile As String = sourceLocation 'set source location after removing unwanted characters
Dim strDestinationFile As String = destinationDirectory & fileName 'set the destination location with the directory and file name
'set ppAPP to a power point application
Dim ppApp As PowerPoint.Application = New PowerPoint.Application
Dim prsPres As PowerPoint.Presentation = ppApp.Presentations.Open(strSourceFile, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse)
'Call the SaveAs method of Presentaion object and specify the format as HTML
prsPres.SaveAs(strDestinationFile, PowerPoint.PpSaveAsFileType.ppSaveAsHTML, MsoTriState.msoTrue)
'Close the Presentation object
prsPres.Close()
'Close the Application object
ppApp.Quit()
End Sub
This gets the file which has been modified and saves it as a html document. It will also get the files needed to run so if any animations have been saved it will also keep those.