' J Server for Excel Client utilities
'
' utilities:
'   jdopen                open JDLLServer
'   jxopen                open JEXEServer
'   jcmd (string)         execute J command, return result
'   jcmdc string,r,c,h,w  execute J command, store result in
'                         active sheet at r,c,height,width
'   jcmdr string, range   execute J command, store result in
'                         active sheet at range
'   jdo string            execute J command
'   jget(x)               get J noun x
'   jloadprofile          load standard J profile
'   jlog boolean          log on/off  (EXE only)
'   jsetc x,r,c,h,w       set J noun x from range (as jcmdc)
'   jsetr x,range         set J noun x from range (as jcmdr)
'   jshow boolean         show on/off (EXE only)
'
' Create in your module an auto_open sub to load J as in:
'
' for the J EXE Server:
'   Sub auto_open()
'   jxopen
'   jloadprofile          - this line optional, for debugging
'   jshow 1               - ditto
'   jlog 1                - ditto
'   End Sub'
'
' for the J DLL Server:
'   Sub auto_open()
'    jdopen
'   End Sub

Public js As Object

Sub jdopen()
On Error GoTo Fini
Set js = CreateObject("jdllserver")
Fini:
End Sub

Sub jxopen()
On Error GoTo Fini
Set js = CreateObject("jexeserver")
js.Quit
Fini:
End Sub

Function jcmd(s As String) As Variant
jdo "JXP=: " & s
jcmd = jget("JXP")
End Function

Sub jcmdc(s As String, r As Integer, c As Integer, h As Integer, w As Integer)
Dim x As Integer, y As Integer
v = jcmd(s)
x = r + h - 1
y = c + w - 1
ActiveSheet.Range(Cells(r, c), Cells(x, y)) = v
End Sub

Sub jcmdr(s As String, r As String)
v = jcmd(s)
ActiveSheet.Range(r) = v
End Sub

Sub jdo(s As String)
ec = js.Do(s)
If ec Then MsgBox "Error code: " & Str(ec)
End Sub

Function jget(s As String) As Variant
ec = js.Get(s, v)
If ec Then MsgBox "Error code: " & Str(ec)
jget = v
End Function

Sub jloadprofile()
jdo "0!:0 <1!:45''"
End Sub

Sub jlog(b As Boolean)
js.Log b
End Sub

Sub jsetc(s As String, r As Integer, c As Integer, h As Integer, w As Integer)
Dim x As Integer, y As Integer
x = r + h - 1
y = c + w - 1
v = ActiveSheet.Range(Cells(r, c), Cells(x, y)).Value
ec = js.Set(s, v)
If ec Then MsgBox "Error code: " & Str(ec)
End Sub

Sub jsetr(s As String, r As String)
v = ActiveSheet.Range(r).Value
ec = js.Set(s, v)
If ec Then MsgBox "Error code: " & Str(ec)
End Sub

Sub jshow(b As Boolean)
js.Show b
End Sub