-
Notifications
You must be signed in to change notification settings - Fork 1
/
SAP.vba
3452 lines (2578 loc) · 127 KB
/
SAP.vba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
' version: 2024-05-10
' Created by Miroslav Suba
'
' GitHub repository - check for updates
' https://github.com/msuba-dev/SAP-GUI-VBA-Excel-scripting
Option Explicit
Option Private Module
'Disconnected - try to log back in
Public Const error_SAP_Disconnected = -2147417848
'Automation error The server threw an expection (occurs ususally when connection drops)
Public Const error_SAP_AutomationError = -2147417851
'The remote procedure failed (occurs ususally when SAP Logon launchpad crashes)
Public Const error_SAP_RemoteProcedureFailed = -2147023170
'The remote server machine does not exist or is unavailable (occurs ususally when SAP Logon launchpad crashes)
Public Const error_SAP_RemoteServerMachineDoesNotExist = 462
'The 'Sapgui Component' could not be instantiated. (occurs when SAP is down)
Public Const error_SAP_GUICouldNotBeInstantiated = 605
'Control could not be found by id. (occurs when SAP is disconnected)
Public Const error_SAP_ControlNotFoundByID = 619
'Logon entry not found
Public Const error_SAP_Logon_EntryNotFound = 1000
Public Const fsForReading = 1
Public Const fsForWriting = 2
Public Const fsForAppending = 8
Private Const moduleVersion = "Q3JlYXRlZCBieSBtc3ViYUBocGUuY29t"
Private Type T_SAP_TreeItemQuery
listIndex As Long
columnValue As String
flagFound As Boolean
End Type
Private Type T_SAP_Client
systemName As String
userName As String
End Type
Private Type T_CachedDate
inputDate As String
outputDate As String
End Type
Public SAPRot As Object
Public SAPGUIAuto As Object
Public SAPApp As Object
Public SAPConnection As Object
Public SAPSystemName As String
Public SAPHwnd As Long
Public filePathSaveAs As String
Public sessionWasLoggedByMacro As Boolean
Public exportTimeOut As Long
'SAP GUI Tree structure for IDocs
'---------------------------------------------------
' Node Key Node Path
'---------------------------------------------------
' IDoc Selection 1
' Idoc Number is equal 1\1
' BCSO Development System D01 2
' Idoc in inbound processing 2\1
' Application document not posted 2\1\1
Public Type T_SAP_TreeNode
nodeKey As String
nodePath As String
nodeItems As Variant
End Type
Public Type T_SAP_TreeColumn
columnName As String
columnTitle As String
End Type
Public Type T_SAP_Tree
SID As String
selectedNodeKey As String
columns() As T_SAP_TreeColumn
listTreeNodes() As T_SAP_TreeNode
End Type
'---
' Speed optimization for functions:
' SAP_LoadAllObjects - used by SAP_GetValidObjectID
'
' passportTransactionID helps us to identify if transaction was changed
' T_SAP_ObjectID - properties of object ID
' listAllSID - all SAP object IDs loaded by SAP_LoadAllObjects
'---
Public passportTransactionID As String
Public Type T_SAP_ObjectID
ID As String
textValue As String
typeValue As String
nameValue As String
changeAble As Boolean
containerType As Boolean
End Type
Public listAllSID() As T_SAP_ObjectID
'
Public SAPSystemID As Long
'
Private listFieldInfo() As Variant
Private listCachedDates() As T_CachedDate
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' SOME INTERNAL FUNCTIONS
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Private Sub FSO_DeleteFile(fileName As String)
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
'Force file deletion, in case file exists already
If fso.FileExists(fileName) Then
'object.DeleteFile filespec, [ force ]
fso.DeleteFile fileName, True
End If
End Sub
Private Function FormatAsFolderPath(ByVal folderPath As String) As String
folderPath = Trim(folderPath)
If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
FormatAsFolderPath = folderPath
End Function
Private Function GetFileExtension(ByVal fileName As String) As String
Dim I As Long
GetFileExtension = ""
If InStr(fileName, ".") > 0 Then
For I = Len(fileName) To 1 Step -1
If Mid(fileName, I, 1) = "." Then
GetFileExtension = Mid(fileName, I + 1, Len(fileName))
Exit Function
End If
Next I
End If
End Function
Function ChangeExtension(ByVal fileName As String, fileExtension As String)
Dim I As Long
If InStr(fileName, ".") > 0 Then
For I = Len(fileName) To 1 Step -1
If Mid(fileName, I, 1) = "." Then
fileName = Mid(fileName, 1, I - 1)
Exit For
End If
Next I
End If
ChangeExtension = fileName & "." & fileExtension
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Function will check if string s is in array v
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Private Function stringIsInArray(ByVal s As String, ByVal v As Variant, Optional caseSensitive As Boolean = False) As Boolean
Dim I As Long
stringIsInArray = False
If IsArray(v) Then
For I = LBound(v) To UBound(v)
If caseSensitive Then
If s = v(I) Then
stringIsInArray = True
Exit Function
End If
Else
If UCase(s) = UCase(v(I)) Then
stringIsInArray = True
Exit Function
End If
End If
Next I
End If
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Function will check if object o is nothing, if yes - it will display errorMsg
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Private Function IsObjectInvalid(ByVal o As Object, ByVal errorMsg As String) As Boolean
IsObjectInvalid = False
If o Is Nothing Then
IsObjectInvalid = True
MsgBox errorMsg, vbCritical, "SAP Initialization Error"
End If
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Function will check if v is numeric value, returns vbNullString if not, otherwise v converted to number
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Private Function GetNumericValue(ByVal v As Variant) As Variant
'Convert to string, remove extra spaces
v = CStr(v)
v = Trim(v)
If IsNumeric(v) Then
v = CLng(v)
Else
v = vbNullString
End If
GetNumericValue = v
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Safe function to get changeAble property (not all objects have this one!)
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Private Function SAP_GetChangeAble(o As Object) As Boolean
Dim listGUIwithChangeAbleProperty As Variant
SAP_GetChangeAble = False
If o Is Nothing Then Exit Function
' Dim listGUIComponentType As Variant
' listGUIComponentType = Array("GuiAbapEditor", "GuiApoGrid", "GuiApplication", "GuiBarChart", "GuiBox", "GuiButton", "GuiCalendar", "GuiChart", "GuiCheckBox", "GuiCollection", "GuiColorSelector", "GuiComboBox", "GuiComboBoxControl", "GuiComboBoxEntry", "GuiComponent", _
' "GuiComponentCollection", "GuiConnection", "GuiContainer", "GuiContainerShell", "GuiContextMenu", "GuiCTextField", "GuiCustomControl", "GuiDialogShell", "GuiEAIViewer2D", "GuiEAIViewer3D", "GuiEnum", "GuiFrameWindow", "GuiGOSShell", "GuiGraphAdapt", _
' "GuiGridView", "GuiHTMLViewer", "GuiInputFieldControl", "GuiLabel", "GuiMainWindow", "GuiMap", "GuiMenu", "GuiMenubar", "GuiMessageWindow", "GuiModalWindow", "GuiNetChart", "GuiOfficeIntegration", "GuiOkCodeField", "GuiPasswordField", "GuiPicture", "GuiRadioButton", _
' "GuiSapChart", "GuiScrollbar", "GuiScrollContainer", "GuiSession", "GuiSessionInfo", "GuiShell", "GuiSimpleContainer", "GuiSplit", "GuiSplitterContainer", "GuiStage", "GuiStatusbar", "GuiStatusPane", "GuiTab", "GuiTableColumn", "GuiTableControl", _
' "GuiTableRow", "GuiTabStrip", "GuiTextedit", "GuiTextField", "GuiTitlebar", "GuiToolbar", "GuiToolbarControl", "GuiTree", "GuiUserArea", "GuiUtils", "GuiVComponent", "GuiVContainer")
'TODO: sort list by usage of objects (will speed up process, I already sorted it a little bit, but there is more to do :))
'Object doesn't support this property or method
'GuiTitlebar
listGUIwithChangeAbleProperty = Array("GuiMenu", "GuiButton", "GuiLabel", "GuiTextField", "GuiCTextField", "GuiStatusPane", "GuiTab", "GuiComboBox", "GuiToolbar", "GuiShell", "GuiCheckBox", "GuiContainerShell", "GuiSimpleContainer", _
"GuiMenubar", "GuiStatusbar", "GuiUserArea", "GuiOkCodeField", "GuiBox", "GuiScrollContainer", "GuiGOSShell", "GuiTableControl", "GuiCustomControl", "GuiDialogShell", _
"GuiEAIViewer2D", "GuiEAIViewer3D", "GuiFrameWindow", "GuiGraphAdapt", "GuiGridView", "GuiHTMLViewer", "GuiMainWindow", "GuiMap", "GuiMessageWindow", _
"GuiModalWindow", "GuiNetChart", "GuiOfficeIntegration", "GuiPasswordField", "GuiRadioButton", "GuiSapChart", "GuiSplit", "GuiSplitterContainer", _
"GuiStage", "GuiTextedit", "GuiToolbarControl", "GuiTree", "GuiVComponent", "GuiVContainer", "GuiAbapEditor", "GuiApoGrid", "GuiBarChart", "GuiCalendar", "GuiChart", "GuiColorSelector", "GuiContextMenu")
If stringIsInArray(Trim(o.Type), listGUIwithChangeAbleProperty) Then
'MsgBox o.type
SAP_GetChangeAble = o.changeAble
End If
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Function converts nodePath
' 1\1\1 --> 1\2
' 1\2\1 --> 1\3
' and so on ...
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function GetNextNodePathParent(ByVal nodePath As String) As String
Dim I As Long
Dim nodeList() As String
Dim nodePathNew As String
nodePathNew = ""
If InStr(nodePath, "\") > 0 Then
nodeList = Split(nodePath, "\")
If UBound(nodeList) > 1 Then
For I = LBound(nodeList) To UBound(nodeList) - 2
If nodePathNew > "" Then nodePathNew = nodePathNew & "\"
nodePathNew = nodePathNew & nodeList(I)
Next I
GetNextNodePathParent = nodePathNew & "\" & Val(nodeList(UBound(nodeList) - 1)) + 1
Else
GetNextNodePathParent = Val(nodeList(UBound(nodeList) - 1)) + 1
End If
Else
GetNextNodePathParent = Val(nodePath) + 1
End If
Erase nodeList
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Function converts nodePath
' 1\1\1 --> 1\1\2
' 1\2\1 --> 1\2\2
' and so on ...
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function GetNextNodePath(ByVal nodePath As String) As String
Dim I As Long
Dim nodeList() As String
Dim nodePathNew As String
nodePathNew = ""
If InStr(nodePath, "\") > 0 Then
nodeList = Split(nodePath, "\")
For I = 0 To UBound(nodeList) - 1
If nodePathNew > "" Then nodePathNew = nodePathNew & "\"
nodePathNew = nodePathNew & nodeList(I)
Next I
GetNextNodePath = nodePathNew & "\" & Val(nodeList(UBound(nodeList))) + 1
Else
GetNextNodePath = Val(nodePath) + 1
End If
Erase nodeList
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' PUBLIC FUNCTIONS
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Function will extract 'clean' SAP object ID
' /app/con[0]/ses[0]/wnd[0]/usr/ctxtVBAK-VBELN --> wnd[0]/usr/ctxtVBAK-VBELN
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function SAP_GetSID(ByVal SID As String, Optional ByVal startsFrom = "wnd[") As String
Dim I As Long
I = InStr(SID, startsFrom)
If I > 0 Then SID = Mid(SID, I)
SAP_GetSID = SID
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Function will extrat last part of SAP object ID
' /app/con[0]/ses[0]/wnd[0]/usr/ctxtVBAK-VBELN --> ctxtVBAK-VBELN
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function SAP_GetLastSID(ByVal SID As String) As String
Do
If InStr(SID, "/") > 0 Then
SID = Mid(SID, InStr(SID, "/") + 1)
End If
Loop While InStr(SID, "/") > 0
SAP_GetLastSID = SID
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Function will get row number from SAP object ID - SID
' wnd[0]/usr/lbl[91,15] --> 15
' [column, row]
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function SAP_GetSIDRow(ByVal SID As String) As Long
Dim I As Long
SAP_GetSIDRow = -1
SID = SAP_GetLastSID(SID)
I = InStr(SID, "lbl[")
If I > 0 Then
SID = Mid(SID, I + 4)
I = InStr(SID, ",")
If I > 0 Then
SID = Mid(SID, I + 1)
I = InStr(SID, "]")
If I > 0 Then
SID = Mid(SID, 1, I - 1)
If IsNumeric(SID) Then SAP_GetSIDRow = Val(SID)
End If
End If
End If
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Function will get column number from SAP object ID - SID
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function SAP_GetSIDCol(ByVal SID As String) As Long
Dim I As Long
SAP_GetSIDCol = -1
SID = SAP_GetLastSID(SID)
I = InStr(SID, "lbl[")
If I > 0 Then
SID = Mid(SID, I + 4)
I = InStr(SID, ",")
If I > 0 Then
SID = Mid(SID, 1, I - 1)
If IsNumeric(SID) Then SAP_GetSIDCol = Val(SID)
Exit Function
End If
End If
For I = Len(SID) To 1 Step -1
If Mid(SID, I, 1) = "[" Then
SID = Mid(SID, I + 1)
I = InStr(SID, ",")
If I > 0 Then
SID = Mid(SID, 1, I - 1)
If IsNumeric(SID) Then SAP_GetSIDCol = Val(SID)
Exit Function
End If
End If
Next I
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Releases all objects from memory used by this module
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Sub SAP_Destroy(vSession As Object, Optional reInit As Boolean = False)
Set vSession = Nothing
'Global SAP variables
Set SAPRot = Nothing
Set SAPGUIAuto = Nothing
Set SAPApp = Nothing
Set SAPConnection = Nothing
passportTransactionID = ""
If reInit = False Then
Erase listCachedDates
End If
Erase listAllSID
End Sub
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Sets filePathSaveAs to Temporary files if not specified by filePath
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Sub SAP_SetFilePathSaveAs(Optional ByVal filePath As String = "")
If filePath = "" Then
filePathSaveAs = Environ("TEMP")
Else
filePathSaveAs = filePath
End If
filePathSaveAs = FormatAsFolderPath(filePathSaveAs)
End Sub
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Will get text from Status bar
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function SAP_GetStatusBar(vSession As Object) As String
Dim s As String
s = vSession.FindByID("wnd[0]/sbar").Text
s = Trim(s)
SAP_GetStatusBar = s
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Will get text from Title
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function SAP_GetTitleBar(vSession As Object) As String
Dim s As String
s = vSession.FindByID("wnd[0]/titl").Text
s = Trim(s)
SAP_GetTitleBar = s
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Will get window ID - winNo = 1 (first 'sub window', e.g. Find Variant)
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function SAP_GetWindowID(vSession As Object, Optional winNo As Long = 0) As String
SAP_GetWindowID = ""
If vSession.Children.Count > winNo Then
'winNo has to be converted to Integer
SAP_GetWindowID = vSession.Children(CInt(winNo)).ID
End If
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Will clear all text fields in Session, in specified area, by default -> wnd[0]/usr
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Sub SAP_ClearAllTextFields(vSession As Object, Optional ByVal searchArea = "wnd[0]/usr")
Dim o As Object
'Clear all text fields
For Each o In vSession.FindByID(searchArea).Children
'Text fields only
If stringIsInArray(Trim(o.Type), Array("GuiTextField", "GuiCTextField")) Then
'If ChangeAble
If o.changeAble = True Then o.Text = ""
End If
Next o
Set o = Nothing
End Sub
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Will get the number of Session, where tCode is active, if there is no such session -1 value will be returned
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function SAP_GetSessionNoByTCode(vSession As Object, tCode As String) As Long
Dim I As Long
SAP_GetSessionNoByTCode = -1
tCode = UCase(Trim(tCode))
'Empty Session
Select Case tCode
Case "0", "SAP EASY ACCESS":
tCode = "SESSION_MANAGER"
End Select
'Init SAP if not done already
If SAPConnection Is Nothing Then SAP_Init vSession, selectEmptySession:=False
If IsObjectInvalid(SAPConnection, "Error while initializing object SAPApp.Children() of GetScriptingEngine") = False Then
For I = 1 To SAPConnection.Children.Count
If SAPConnection.Children(CInt(I - 1)).Busy = False Then
'SessionNo has to be converted to Integer
Set vSession = SAPConnection.Children(CInt(I - 1))
If UCase(Trim(vSession.Info.Transaction)) = tCode Then
SAP_GetSessionNoByTCode = I
Exit Function
End If
End If
Next I
End If
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Will get the number of Session, where tCode is active, if there is no such session -1 value will be returned
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function SAP_GetSessionNoByProgramName(vSession As Object, programName As String) As Long
Dim I As Long
SAP_GetSessionNoByProgramName = -1
programName = UCase(Trim(programName))
'Init SAP if not done already
If SAPConnection Is Nothing Then SAP_Init vSession, selectEmptySession:=False
If IsObjectInvalid(SAPConnection, "Error while initializing object SAPApp.Children() of GetScriptingEngine") = False Then
For I = 1 To SAPConnection.Children.Count
If SAPConnection.Children(CInt(I - 1)).Busy = False Then
'SessionNo has to be converted to Integer
Set vSession = SAPConnection.Children(CInt(I - 1))
If UCase(Trim(vSession.Info.Program)) = programName Then
SAP_GetSessionNoByProgramName = I
Exit Function
End If
End If
Next I
End If
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Will log in to SAP session via specified connectionName, with specified userName and password
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Sub SAP_OpenConnection(vSession As Object, ByVal connectionName As String, Optional userName As String = "", Optional password As String = "", Optional synchronousMode As Boolean = True)
Dim response As Variant
Dim flagCriticalError As Boolean
TryAgain:
flagCriticalError = False
Set SAPGUIAuto = GetObject("SAPGUI")
'Set SAPGUIAuto = CreateObject("SAPGUI")
'Set SAPGUIAuto = CreateObject("SAPGUI.ScriptingCtrl.1")
Set SAPApp = SAPGUIAuto.GetScriptingEngine()
On Error Resume Next
Set SAPConnection = SAPApp.OpenConnection(connectionName, synchronousMode)
If Err.Number = error_SAP_GUICouldNotBeInstantiated Then
flagCriticalError = True
response = MsgBox(connectionName & " connection could not be instantiated." & Chr(10) & "SAP is probably down." & Chr(10) & "Do you want to try again?", vbCritical + vbYesNo, "SAP open connection")
If response = vbYes Then GoTo TryAgain
End If
If Err.Number = error_SAP_Logon_EntryNotFound Then
flagCriticalError = True
MsgBox "SAP Logon connection entry not found " & connectionName, vbCritical, "SAP open connection"
End If
If Err.Number <> 0 Then Err.Clear
On Error GoTo -1
If flagCriticalError Then Exit Sub
'---
Set vSession = SAPConnection.Children(0)
'Wait for window to appear
Do
Application.Wait (Now + TimeValue("00:00:01"))
DoEvents
Loop While vSession.Info.Transaction <> "S000"
'If username and password are specified - enter them
If userName <> "" Then vSession.FindByID("wnd[0]/usr/txtRSYST-BNAME").Text = userName
If password <> "" Then vSession.FindByID("wnd[0]/usr/pwdRSYST-BCODE").Text = password
If userName <> "" And password <> "" Then vSession.FindByID("wnd[0]/tbar[0]/btn[0]").Press
Do
Application.Wait (Now + TimeValue("00:00:01"))
'License Information for Multiple Logon
Dim SID As String
SID = SAP_GetWindowID(vSession, 1)
If SID <> "" Then
If vSession.FindByID(SID).Text = "License Information for Multiple Logon" Then
'TODO: macro waits for user action
End If
End If
DoEvents
Loop While UCase(Trim(vSession.Info.Transaction)) <> "SESSION_MANAGER"
sessionWasLoggedByMacro = True
End Sub
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
' Method will connect vSession object to SAP session
' by specifying systemName you can connect to specific system (eg: R01, DCP). If not specified user will be prompted to select system manually
' by specifying sessionNo you can connect to specific session
' by default function will try to connect to empty session (with SESSION_MANAGER)
'---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Sub SAP_Init(vSession As Object, Optional systemName As String = "", Optional sessionNo As Long = -1, Optional selectEmptySession As Boolean = True, Optional selectHwnd As Long = 0)
Dim I As Long
Dim J As Long
Dim SID As String
Dim listClients() As T_SAP_Client
Dim listClientsCount As Long
Dim sessionsCount As Long
Dim hwnd As String
Dim flagNewHandle As Boolean
Dim listHandles() As String
Dim title As String
Dim msg As String
Dim response As Variant
Dim isBusy As Boolean
Dim defaultClient As String
Dim sessionCreated As Boolean
'--
ReDim listCachedDates(0)
listCachedDates(0).inputDate = ""
listCachedDates(0).outputDate = ""
TryAgain_Disconnected:
SAP_Destroy vSession, reInit:=True
'export time out 1 hour in case of MHTML files
exportTimeOut = 3600
On Error Resume Next
'Try to connect using SAP ROT Wrapper
Set SAPRot = CreateObject("SapROTWr.SapROTWrapper")
Set SAPGUIAuto = SAPRot.GetROTEntry("SAPGUI")
Err.Clear
'If it does not work this way, try default
If SAPGUIAuto Is Nothing Then
Set SAPGUIAuto = GetObject("SAPGUI")
If IsObjectInvalid(SAPGUIAuto, "Error while initializing object SAPGUI." & Chr(10) & "Please make sure SAP Logon Launchpad is running.") Then GoTo Error_Handler
End If
Set SAPApp = SAPGUIAuto.GetScriptingEngine()
If IsObjectInvalid(SAPApp, "Error while initializing object GetScriptingEngine of SAPGUI.") Then GoTo Error_Handler
'Detect Clients
listClientsCount = SAPApp.Children.Count
If listClientsCount = 0 Then
title = "SAP Initialization Error"
If systemName <> "" Then
title = title & " (" & systemName & ")"
End If
response = MsgBox("You are not logged in." & Chr(10) & "Do you want to log in now?", vbCritical + vbYesNo, title)
If response = vbYes Then GoTo Open_New_Connection
GoTo Exit_Program
End If
ReDim listClients(listClientsCount)
For I = 1 To listClientsCount
isBusy = True
'We will ignore busy clients
For J = 0 To SAPApp.Children(CInt(I - 1)).Children.Count - 1
If SAPApp.Children(CInt(I - 1)).Children(CInt(J)).Busy = False Then
'SessionNo has to be converted to Integer
listClients(I).systemName = Trim(SAPApp.Children(CInt(I - 1)).Children(CInt(J)).Info.systemName)
listClients(I).userName = Trim(SAPApp.Children(CInt(I - 1)).Children(CInt(J)).Info.user)
isBusy = False
Exit For
End If
Next J
If isBusy Then
listClients(I).systemName = "[session is busy]"
End If
Next I
'if scripting is not enabled - Info.User will not be available and will raise an error
Err.Clear
msg = ""
response = ""
defaultClient = "1"
'If user specified to which Client he wants to connect with
If systemName <> "" Then
For I = 0 To listClientsCount
If listClients(I).systemName Like systemName Then
response = I
Exit For
End If
Next I
If response = "" Then
msg = "Client " & systemName & " not detected." & Chr(10)
defaultClient = "+"
End If
End If
'In case that more then one client is available
If response = "" Then
If listClientsCount > 1 Then
msg = msg & "More than one SAP connection is available." & Chr(10)
End If
End If
'If there is any 'warning' msg in variable msg then User has to select with which client he would like to be connected
'(either he did not specify client and we have more of them available, or he specified a different client than the one which is available)
If msg <> "" Then
msg = msg & "Select client, you would like to connect with:"
'Create a list of clients
For I = 1 To listClientsCount
msg = msg & Chr(10) & I & " - " & listClients(I).systemName & " " & listClients(I).userName
Next I
msg = msg & Chr(10) & "+ - to open new connection."
response = InputBox(msg, "SAP Initialization", defaultClient)
'+ open new connection
If response = "+" Then
Open_New_Connection:
response = InputBox("Please enter Logon entry name:", "SAP Logon connection entry", systemName)
If response <> "" Then
'User will have to enter
SAP_OpenConnection vSession, response
If SAP_Activated(vSession, systemName) = False Then GoTo Exit_Program
Set SAPConnection = vSession.Parent
GoTo New_Connection_Opened
End If
End If
response = GetNumericValue(response)
If response = "" Then GoTo Exit_Program
'Wrong input ?
If (response < 1) Or (response > listClientsCount) Then
response = ""
MsgBox "Wrong input !", vbCritical, "SAP Initialization Error"
End If
Else
'And of course, if there is one client available, we will connect to that one
If response = "" Then response = 1
End If
Set SAPConnection = SAPApp.Children(CInt(response - 1))
If IsObjectInvalid(SAPConnection, "Error while initializing object SAPApp.Children() of GetScriptingEngine") Then GoTo Error_Handler
If SAPConnection.DisabledByServer Then
MsgBox "Scripting support has not been enabled for the application server." & Chr(10) & _
Trim(SAPConnection.connectionstring), vbCritical, "SAP Initialization error"
GoTo Exit_Program
End If
On Error GoTo -1
'Detect Session no (we can create new session with this function)
New_Connection_Opened:
ReDim listHandles(0): listHandles(0) = ""
sessionsCount = SAPConnection.Children.Count
'Not specified by user - connect to first session
If sessionNo = -1 Then
sessionNo = 1
Else
'Check if sessionNo is within boundaries (1 to number of sessions)
If sessionNo < 1 Then
sessionNo = 1
End If
End If
'Check if session is busy - increase session number if it is
Dim handleFound As Boolean
handleFound = False
SearchForValidSession:
If sessionNo <= sessionsCount Then
For I = 1 To sessionsCount
'Keep track of currently opened session window handles
If SAPConnection.Children(CInt(I - 1)).Busy = False Then
If listHandles(0) <> "" Then ReDim Preserve listHandles(UBound(listHandles) + 1)
listHandles(UBound(listHandles)) = SAPConnection.Children(CInt(I - 1)).ActiveWindow.Handle
End If
If sessionNo = I Then
If SAPConnection.Children(CInt(I - 1)).Busy Then
sessionNo = sessionNo + 1
Else
If selectHwnd <> 0 Then
If selectHwnd = SAPConnection.Children(CInt(I - 1)).ActiveWindow.Handle Then
handleFound = True
sessionNo = I
Exit For
End If
Else
If selectEmptySession Then
If SAPConnection.Children(CInt(I - 1)).Info.Transaction <> "SESSION_MANAGER" Then
sessionNo = sessionNo + 1
End If
End If
End If
End If
End If
Next I
End If
If selectHwnd <> 0 Then
If handleFound = False Then
selectHwnd = 0
GoTo SearchForValidSession
End If
End If
'Create New Session if needed
If sessionNo > sessionsCount Then
sessionCreated = False
'Wait till new Session will be created
Do
'It is impossible to create new session if session from which we are creating it is busy - we still have to wait (nooooo ;-/)
If sessionCreated = False Then
'Try to create session - hopefully one of currently opened sessions is not busy
'(otherwise we have to wait for user to do it manually)
isBusy = True
For I = 1 To sessionsCount
Set vSession = SAPConnection.Children(CInt(I - 1))
If vSession.Busy = False Then
isBusy = False
sessionCreated = True
'List of Children changes when new session is created - list is sorted by hwnd!
vSession.CreateSession
While vSession.Busy
DoEvents
Wend
Exit For
End If
Next I
If isBusy Then
'Let user know that all SAP sessions are currently busy!
Application.StatusBar = "SAP_Init: all sessions are currently busy! (... you can create new session manually)"
End If
Else
If vSession.Busy = False Then
SID = SAP_GetWindowID(vSession, 1)
If SID <> "" Then
If vSession.FindByID(SID).Text = "Information" Then
If vSession.FindByID("wnd[1]/usr/txtMESSTXT1").Text = "Maximum number of sessions reached" Then
MsgBox "Maximum number of sessions reached", vbCritical, "SAP Initialization Error"
vSession.FindByID(SID).Close
GoTo Exit_Program
End If
End If
End If
End If
End If
'-- Check if we have new window available
'Update variables
sessionsCount = SAPConnection.Children.Count
sessionNo = sessionsCount
For I = 1 To sessionsCount
'Only if not busy
If SAPConnection.Children(CInt(I - 1)).Busy = False Then
flagNewHandle = True
'Get window handle
hwnd = SAPConnection.Children(CInt(I - 1)).ActiveWindow.Handle
'Check which session window is new
For J = LBound(listHandles) To UBound(listHandles)
If listHandles(J) = hwnd Then
flagNewHandle = False
Exit For
End If
Next J
If flagNewHandle Then
'We have to check also tcode ... newly opened session should have opened by default SESSION_MANAGER
If SAPConnection.Children(CInt(I - 1)).Info.Transaction = "SESSION_MANAGER" Then
sessionNo = I
Set vSession = SAPConnection.Children(CInt(I - 1))
Exit For
End If
End If
End If
Next I
If sessionsCount = 0 Then
'SAP crashed while we tried to create new session ...
'MsgBox "booom"
GoTo TryAgain_Disconnected
End If
DoEvents
Loop While flagNewHandle = False
Else
Set vSession = SAPConnection.Children(CInt(sessionNo - 1))
End If
Err.Clear