Using Cosign SAPI COM DLL in VBA for Word 2010 - cosign-api

I am just learning to use CoSign SAPI. I down loaded the example VB.Net program code for Visual Studio and it runs ok. I then tried to run code in Microsoft Word 2010 as a VBA module. The code executes ok up to the SAPI.logon statement and fails. Below is the code I am using. Also, do you know of any other example programs using SAPICom in Word VBA? Thanks very much for your help.
Public Sub testCoSign()
Const SAPI_OK As Integer = 0
Dim rc As Integer
Dim SAPI As New SAPICrypt
Dim sesMyHandle As New sesHandle
'Custom Values
Dim filePath As String 'PDF file to sign
Dim username As String 'CoSign account username
Dim password As String 'CoSign account password
Dim domain As String 'CoSign account domain
Dim sigPageNum As Integer 'Create signature on the first page
Dim sigX As Integer 'Signature field X location
Dim sigY As Integer 'Signature field Y location
Dim sigWidth As Integer 'Signature field width
Dim sigHeight As Integer 'Signature field height
Dim timeFormat As String 'Time appearance format mask
Dim dateFormat As String 'Date appearance format mask
Dim appearanceMask As Integer 'Elements to display on the signature field
'Initialize variables
Set sesMyHandle = Nothing
filePath = "c:\\temp\\demo.doc"
username = "JSMITH"
password = "*******"
sigPageNum = 1
sigX = 145
sigY = 125
sigWidth = 160
sigHeight = 45
timeFormat = "hh:mm:ss"
dateFormat = "dd/MM/yyyy"
appearanceMask = SAPI_ENUM_DRAWING_ELEMENT.SAPI_ENUM_DRAWING_ELEMENT_GRAPHICAL_IMAGE Or _
SAPI_ENUM_DRAWING_ELEMENT.SAPI_ENUM_DRAWING_ELEMENT_SIGNED_BY Or _
SAPI_ENUM_DRAWING_ELEMENT.SAPI_ENUM_DRAWING_ELEMENT_TIME
' Initialize SAPI library
rc = SAPI.Init
If rc <> SAPI_OK Then
MsgBox "error initializing SAPI", vbOKOnly, "Error"
End If
' Acquire SAPI session handle
rc = SAPI.HandleAcquire(sesMyHandle)
If rc <> SAPI_OK Then
MsgBox "error acquiring SAPI session handle", vbOKOnly, "Error"
End If
' Personalize SAPI Session
rc = SAPI.Logon(sesMyHandle, username, "", password)
If rc <> SAPI_OK Then
MsgBox "failure to authenticate user", vbOKOnly, "Error"
End If
End Sub

The code is woking now. The problem was due to invalid user account; I didn't realize the user account is case sensitive. After entering the user account name correctly the code is now working.
I also changed the code for instantiating the SAPI objects to the following, but the original code was not causing a problem.
Dim SAPI As SAPICrypt
Set SAPI = New SAPICrypt
Dim sesMyHandle As sesHandle
Set sesMyHandle = Nothing
Thanks for your help.

I don’t think you can call SAPI COM from VBA (basically a script from within Word). Can you try running your VB.Net as an independent application?

Related

Email body is empty without .Display

I've read this: VBA Outlook 2010 received mail .Body is empty but it is old and the other question referenced in the answer(s) is not found when I click on it.
Here's my basic code.
Sub AutoReplyTrap(objInMail As MailItem)
Dim objOutMail As Outlook.MailItem
Dim vText As Variant
Dim sText As String
Dim strID As String
Dim sSubject As String
Dim vItem As Variant
Dim vFirstName As Variant
Dim i As Long
Dim j As Integer
Dim strSignature As String
Dim strSigString As String
Dim strFirstName As String
Dim strFirstLetter As String
Dim strEMailAddress As String
Dim blnFirstName As Boolean
Dim blnEMail As Boolean
' change the bodyformat to plain text
objInMail.BodyFormat = Outlook.OlBodyFormat.olFormatPlain
objInMail.Display
blnFirstName = False
blnEMail = False
j = 0
' believe there is a timing issue that Body may not be fully loaded.
' so I'm going to pause and loop through 20 times to see if it gets loaded.
WaitForBody:
sText = objInMail.Body
If sText = "" Then
If j < 20 Then
j = j + 1
Sleep 1000
GoTo WaitForBody
End If
End If
If sText = "" Then
MsgBox ("No body in email!")
Exit Sub
End If
End Sub
I thought it was a timing issue, so I built the loop to test if I have the body, and if not, wait a second and try again up to 20 times.
I have objInMail.Display it works, but if I remove that line it will loop through the 20 attempts.
I could live with the display if I could then "un-display" it, but I wonder if the .close will close everything with the email and I'll lose the body again.
I'd prefer it to work without the objInMail.Display.
Ignoring the cause, this may provide a workaround without .Display.
Option Explicit
Private Sub test_GetInspector()
Dim currSel As Object
Set currSel = ActiveExplorer.Selection(1)
If currSel.Class = olMail Then
AutoReplyTrap_GetInspector currSel
End If
End Sub
Sub AutoReplyTrap_GetInspector(objInMail As mailItem)
' change the bodyformat to plain text
objInMail.BodyFormat = OlBodyFormat.olFormatPlain
' objInMail.GetInspector ' Previously "valid".
' My setup finally caught up and provided the clue.
' Directly replacing .Display with .GetInspector
' Compile error:
' Invalid use of property
' https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.getinspector
Dim objInspector As Inspector
Set objInspector = objInMail.GetInspector
' You should find this is necessary
'objInMail.Save
End Sub
Working with Outlook 2010 right now and have an update. The issue is caused by a bug in Outlook 2010/2013 that only gives a blank message body in VBA when:
(1) using IMAP protocol; and,
(2) automatically processing incoming emails.
This holds true even if you just set a Rule from the front end, such as automatically printing specific incoming emails (my task). This prints the email header, not the body.
A workaround that worked for me was to use POP3 protocol instead of IMAP with the same email server.

Outlook VBA add hyperlink of chosen file in dialog

I'm trying to add the functionality in my Outlook (with VBA, I guess is easiest) to add a simple file dialog which takes the path of any files chosen and adds them to the email body as a hyperlink.
The idea of this is for network files to be shared amongst colleagues, instead of attaching them to the email, but just as easy to do.
This is my code so far, I can't even get the dialog to open, and I've had a good look at trying to get COMDLG32.ocx, so far I can't seem to make anything work.
Sub Main2()
Dim CDLG As Object
Set CDLG = CreateObject("MSComDlg.CommonDialog")
With CDLG
.DialogTitle = "Get me a File!"
.Filter = _
"Documents|*.doc|Templates|*.dot|Text Files|*.txt"
.ShowOpen
MsgBox .FileName
End With
Set CDLG = Nothing
End Sub
Thanks in advance, hopefully someone can show me how this is done!
Just for those who need it; OS Windows 10, Office 2010 H&B (yes, I know it's out of date :))
There seems to be no direct way to open a FileDialog in Outlook 2010 VBA.
The following macro (inspired by a related post) makes use of Excel to circumvent this:
Public Function promptFileName(title As String, filter As String) As String
' requires project reference to "Microsoft Excel 14.0 Object Library"
Dim xlObj As Excel.Application
Dim fd As Office.FileDialog
Dim name As String
Dim vItem As Variant
Dim filterArray() As String
Dim i As Integer
Set xlObj = New Excel.Application
xlObj.Visible = False
Set fd = xlObj.Application.FileDialog(msoFileDialogOpen)
name = ""
With fd
.title = title
.ButtonName = "Ok"
.Filters.Clear
filterArray = Split(filter, "|")
For i = LBound(filterArray) To UBound(filterArray) - 1 Step 2
.Filters.Add filterArray(i), filterArray(i + 1), 1 + i \ 2
Next i
If .Show = -1 Then
For Each vItem In .SelectedItems
name = vItem
Exit For
Next
End If
End With
xlObj.Quit
Set xlObj = Nothing
promptFileName = name
End Function
Private Sub testPromptFile
Dim name as String
name = promptFileName("a test", "Text Files (*.txt)|*.txt|All Files (*.*)|*.*")
MsgBox name
End Sub
Outlook 2013 and beyond provide an Office.FileDialog class for this purpose.
You can press a button with Outlook VBA.
Sub ExecuteMso_strId()
Dim objItem As Object
Dim strId As String
' Text appears when hovering over icon
' when adding buttons to a Quick Access toolbar or a ribbon
strId = "HyperlinkInsert"
On Error Resume Next
Set objItem = ActiveInspector.currentItem
On Error GoTo 0
If Not objItem Is Nothing Then
ActiveInspector.CommandBars.ExecuteMso (strId)
Else
ActiveExplorer.CommandBars.ExecuteMso (strId)
End If
End Sub
With this you do not have access to the parameters as with Excel.

Copying from Internet Explorer text area (box) but into more than a single cell

I'm currently trying to control/automate a postcode looking website from postcodes stored and updated in Excel, and my code works perfectly up to the point it has to copy the data once it's finished. For the life of me I can't figure out how to copy the data from the text box / area into Excel without it just putting it ALL into one cell (Text to Columns doesn't really work either).
The website is : http://www.doogal.co.uk/DrivingDistances.php
Sub Geo2()
Dim sht As Worksheet
Dim IE As Object
'Dim ieDoc As HTMLDocument
Dim Item As Variant
Dim objElement As Object
Dim startLoc As String
Dim endLoc As String
Dim x As Integer
Dim objNotes As Object
Dim strNotes As String
Dim str As String
'Dim SignInButton As HTMLInputButtonElement
Set sht = ThisWorkbook.Sheets("Postcode")
Set IE = CreateObject("InternetExplorer.Application")
'Open IE
IE.Visible = True
IE.Navigate "http://www.doogal.co.uk/DrivingDistances.php"
'Wait until site is loaded
Do While IE.ReadyState <> 4 'READYSTATE_COMPLETE
DoEvents
Loop
IE.Document.getElementbyID("startLocs").Value = "dn1 5pq" 'random postcode
IE.Document.getElementbyID("endLocs").Value = "wf12 2fd" 'random postcode
IE.Document.getElementsByName("calculateFor").Item(1).Checked = True
IE.Document.getElementsByName("units").Item(1).Checked = True
IE.Document.getElementsByClassName("btn btn-primary").Item(0).Click
------
'Ive tried without having it as a object and using .value but it either comes with only the first line or the entire thing rammed into a string and is unusable
----Code here is the problem-----
***Set objNotes = IE.Document.getElementbyID("distances")
str = objNotes.Value***
---------
Do While IE.ReadyState <> 4 'READYSTATE_COMPLETE
DoEvents
Loop
End Sub
The following VBA function uses the Google Maps Directions API to calculate the driving distance in meters between two locations. The code is modified from a version submitted by barrowc on this similar question.
Make sure to add a reference in Excel to Microsoft XML, v6.0.
Function getDistance(origin As String, destination As String) As String
Dim xhrRequest As XMLHTTP60
Dim domDoc As DOMDocument60
Dim ixnlDistanceNode As IXMLDOMNode
Dim RequestString As String
Dim API_Key As String
' Insert your own Google Maps Directions API key here
API_Key = "XXXXXX"
' Read the data from the website
Set xhrRequest = New XMLHTTP60
RequestString = "https://maps.googleapis.com/maps/api/directions/xml?origin=" _
& origin & "&destination=" & destination & "&sensor=false&key=" & API_Key
xhrRequest.Open "GET", RequestString, False
xhrRequest.send
' Copy the results into a format we can manipulate with XPath
Set domDoc = New DOMDocument60
domDoc.LoadXML xhrRequest.responseText
' Select the node called value underneath the leg and distance parents.
' The distance returned is the driving distance in meters.
Set ixnlDistanceNode = domDoc.SelectSingleNode("//leg/distance/value")
getDistance = ixnlDistanceNode.Text
Set ixnlDistanceNode = Nothing
Set domDoc = Nothing
Set xhrRequest = Nothing
End Function
Please note that this code by itself violates the Terms of Use of Google's API. "The Google Maps Directions API may only be used in conjunction with displaying results on a Google map; using Directions data without displaying a map for which directions data was requested is prohibited."1
Instead of putting the data all in one string, Split the string into an array, then loop through the array like this:
Set objNotes = IE.Document.getElementbyID("distances")
Dim x as Integer
Dim aDist() as Variant
aDist = Split(objNotes.Value, vbNewLine) 'May need to be vbCr or vbLf or vbCrLf
For x = 0 to Ubound(aDist) - 1
debug.print aDist(x)
Next x

Gah!! Error 424 runtime error : Object required Word Visual Basic

Im trying to load the contents of a textfile into a variable but I get the titular error, searching the VBA knowledgebase led me to belive that
Set mySQL = My.Computer.FileSystem.ReadAllText("C:\sql_query_temp.res")
Would solve it but that just produces 'Error : Object Required' when I run. Heres my code, what have I missed?
'Requires Microsoft ActiveX Data Objects x.x library in references
Public Sub ConnectToOdbc()
Dim myconn As New ADODB.Connection
Dim myrs As New Recordset
Dim mySQL As String
Dim myrows As Long
'Open file containing SQL query
mySQL = My.Computer.FileSystem.ReadAllText("C:\sql_query_temp.res") <----- bad!
'Open Connection
myconn.Open "DSN=database"
'Do Query
myrs.Source = mySQL
Set myrs.ActiveConnection = myconn
myrs.CursorLocation = adUseClient
myrs.Open
'Count Rows
myrows = myrs.RecordCount
'Add text to word document!
Selection.TypeText (myrows)
'Close Connection
myrs.Close
myconn.Close
End Sub
My.Computer is VB.NET which is entirely different from VBA instead you can;
Function readFile(path As String) As String
Dim hF As Integer
hF = FreeFile()
Open path For Input As #hF
readFile = Input$(LOF(hF), #hF)
Close #hF
End Function
...
mySQL = readFile("C:\sql_query_temp.res")
I think this might work.
It will allow you to search any given directory rather than fixating on just the one. This directory is then placed onto the variable 'inFileName'
inFileName = Application.GetOpenFilename("Text & r01 Files(*.*),*.*", , "Open Neutral File", "OPEN)
Hope this helps.

Send SMS via VoipBuster using VBA

I am total beginner, but I am trying to make a macro in VBA to send an SMS using VoipBuster platform when a condition is completed.
Is it possible? Is it easier to use the application installed on PC or web page (https://www.voipbuster.com/sms).
Please help!
For send sms from voipbuster you can send it by php vars...
"https://www.voipbuster.com/myaccount/sendsms.php?username=$USER&password=$PASS&from=$FROM&to=\"$TO\"&text=$SMS_TEXT"
So you need to access iexplore from vba like this , create you vars use, pass, text etcc and concat everythins like the URL before ..
to call iexplore from VBA you will find a lot of ways with google , here you got an example
Private Sub IE_Autiomation()
Dim i As Long
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = False
' Send the form data To URL As POST binary request
IE.Navigate "https://www.voipbuster.com/myaccount/sendsms.php?username=$USER&password=$PASS&from=$FROM&to=\"$TO\"&text=$SMS_TEXT"
Try below code. You can also test by putting the value in URL variable to your browser.
Sub SendSms()
Dim username As String
Dim password As String
Dim sendTo As String
Dim msg As String
username = "test" 'enter username here
password = "test" 'enter password here
sendTo = "9999999999"
msg = "Hello"
Dim URL As String
URL = "https://www.voipbuster.com/myaccount/sendsms.php?username=" & username & "&password=" & password & "&to=" & sendTo & "&text=" & msg
Dim xml As Object
Set xml = CreateObject("MSXML2.XMLHTTP")
xml.Open "GET", URL, False
xml.send
End Sub