Sap to excel macro

This was my first main automation in Excel VBA. I was working a lot on SAP data and modifying it in Excel on the daily basis. Almost every day tons of same routine for get the data. One day I thought to myself about automation. I knew that I can record my activity in Excel, but did not know at all how to connect to SAP using Excel VBA?

Connect to SAP via Excel VBA

Open SAP application

Firstly, if we don’t want to open SAP manually, we need to provide its directory.

'Change for your file directory
Shell "C:Program Files (x86)SAPFrontEndSAPguisaplogon.exe", 4
Set WshShell = CreateObject("WScript.Shell")

Then just wait for the activation of application, because sometimes it can lasts longer than usually.

Do Until WshShell.AppActivate("SAP Logon ")
    Application.Wait Now + TimeValue("0:00:01")
Loop

Set SAP app as object

After that we should set some objects to handle SAP.

Set SapGui = GetObject("SAPGUI")
Set Appl = SapGui.GetScriptingEngine
Set Connection = Appl.Openconnection("paste name of module", True)
Set session = Connection.Children(0)

In Connection object put the name of the module you want to connect (from the SAP Logon Module screen below). It is important to put proper name, in other case You won’t connect.

Connect to SAP via Excel VBA

Log in with the data

In my case there was no need to login and write password, but if it is neccessary in your case I am also prepared for that.

SAP Login Password
SAP Login interface
'if You need to pass username and password
session.findById("wnd[0]/usr/txtRSYST-MANDT").Text = "100"
session.findById("wnd[0]/usr/txtRSYST-BNAME").Text = "user"
session.findById("wnd[0]/usr/pwdRSYST-BCODE").Text = "password"
session.findById("wnd[0]/usr/txtRSYST-LANGU").Text = "EN"

In first row there is unit number, in second put your user login, in third your password and in the last row choose language.

Check if it’s already opened

I also implemented to my SAP code check if it is already opened.

If session.Children.Count > 1 Then

    answer = MsgBox("You've got opened SAP already," & _
"please leave and try again", vbOKOnly, "Opened SAP")

    session.findById("wnd[1]/usr/radMULTI_LOGON_OPT3").Select
    session.findById("wnd[1]/usr/radMULTI_LOGON_OPT3").SetFocus
    session.findById("wnd[1]/tbar[0]/btn[0]").press

    Exit Sub

End If

In the end of connection, code is approving all the things from above and You are ready to do anything SAP.

session.findById("wnd[0]").maximize
session.findById("wnd[0]").sendVKey 0

After that You can put your code, which is operating in SAP system. You can do this for example by script recording in Options.

Full code:

Sub SapConn()

Dim Appl As Object
Dim Connection As Object
Dim session As Object
Dim WshShell As Object
Dim SapGui As Object

'Of course change for your file directory
Shell "C:Program Files (x86)SAPFrontEndSAPguisaplogon.exe", 4
Set WshShell = CreateObject("WScript.Shell")

Do Until WshShell.AppActivate("SAP Logon ")
    Application.Wait Now + TimeValue("0:00:01")
Loop

Set WshShell = Nothing

Set SapGui = GetObject("SAPGUI")
Set Appl = SapGui.GetScriptingEngine
Set Connection = Appl.Openconnection("paste name of module", _
    True)
Set session = Connection.Children(0)

'if You need to pass username and password
session.findById("wnd[0]/usr/txtRSYST-MANDT").Text = "900"
session.findById("wnd[0]/usr/txtRSYST-BNAME").Text = "user"
session.findById("wnd[0]/usr/pwdRSYST-BCODE").Text = "password"
session.findById("wnd[0]/usr/txtRSYST-LANGU").Text = "EN"

If session.Children.Count > 1 Then

    answer = MsgBox("You've got opened SAP already," & _
"please leave and try again", vbOKOnly, "Opened SAP")

    session.findById("wnd[1]/usr/radMULTI_LOGON_OPT3").Select
    session.findById("wnd[1]/usr/radMULTI_LOGON_OPT3").SetFocus
    session.findById("wnd[1]/tbar[0]/btn[0]").press

    Exit Sub

End If

session.findById("wnd[0]").maximize
session.findById("wnd[0]").sendVKey 0 'ENTER

'and there goes your code in SAP

End Sub

Summary

It took me couple of hours to find information in web how to connect to SAP via Excel VBA and finally set this up as code. After that I was only doing copy paste that to my next macros.

I just wanted to save your time, because I know how long and painful was that for me.

This code already helped one guy from StackOverflow – I hope it will help You too.

I also invite you to the next article in this series!
SAP session.findbyid – 10 code lines you can identify

I’m very advanced in VBA, Excel, also easily linking VBA with other Office applications (e.g. PowerPoint) and external applications (e.g. SAP). I take part also in RPA processes (WebQuery, DataCache, IBM Access Client Solutions) where I can also use my SQL basic skillset. I’m trying now to widen my knowledge into TypeScript/JavaScript direction.
View all posts by Tomasz Płociński

Содержание

  1. Interactive and dynamic Excel VBA template – SAP GUI Scripting –
  2. Best Practices for VBA in SAP BI Analysis for MS Excel
  3. How to access SAP using Excel VBA?
  4. 2 Answers 2
  5. SAP Intelligent RPA: Reading Data from Excel using VBA Excel reference properties
  6. What will you learn in this blog:
  7. Brief on Excel VBA reference that would be used to get all the Values without any Loops:
  8. Steps to follow:
  9. Prerequisites:
  10. Instructions:
  11. 1. Create a project
  12. 2. Create a new workflow
  13. 3.Import Excel Library Scripts
  14. 4. Designing Workflow with Custom Scripts
  15. 5. Display Range address and Random Cell Value
  16. Conclusion

Interactive and dynamic Excel VBA template – SAP GUI Scripting –

SAP GUI Scripting can be used for many small and intermediate batches for mass maintenance tasks (P-/Q- and D-Systems) and quality testing (Q-Systems) in SAP.

To reduce development workload or modify a lot of code for different SAP GUI recordings I saw a need for having an Excel VBA template which can cover a lot of requirements.

  • Easy to use (One-Button-Solution).
  • Excel functions and options can be used for data preparation and consolidation in front of starting update procedure.
  • During initialization all existing and non-busy SAP sessions got displayed (UI-Listbox). So we are able to select a specific session for Excel VBA adoption.
  • Data from SAP can easily imported into Excel worksheet (Data from ALV-list, fields, result list, status messages, error messages,… and so on).
  • Only SAP GUI Scripting recording code need to integrate into VBA module ‘SAP_1_PROCESS’.
  • More columns as data source or destination for field data can be added. Last two columns are reserved for procedure usage. This is achieved by using a data-array which got ‘Redim’ during process according to used rows and columns.
  • Log-function is integrated (for SAP messages like statusbar Messages or free-text).

Prepare Excel VBA template:

  1. Step: Create folder on your desktop (or somewhere else) => folder name is up to you.
  2. Step: Store below text-files into this folder: Please be aware that text-file ‘Modules_All.txt’ need to split into four text-files named ‘SAP_1_Process’, ‘SAP_2_Functions’. SAP_3_Public_Subs’ and ‘Module1’! Start and end of module specific coding is marked and must removed before saving of single text-file. First line in this files must be Attribute VB_Name = “SAP_1_Process”, Attribute VB_Name = “SAP_2_Functions” and Attribute VB_Name = “SAP_3_Public_Subs”. As I can´t upload more than three files you Need to split Modules_All.txt on your own and save files in folder.
    1. SAP_1_Process.txt
    2. SAP_2_Functions.txt
    3. SAP_3_Public_Subs.txt
    4. Userform1_frm.txt
    5. Userform1_frx.txt
    6. Module1.txt
  3. Step: Create a new Excel workbook and store this in same folder as text-files. You can choice every name you want. My suggestion is ‘Prepare_WB.xlsx’.
  4. Step: Now go into VBE of Excel ( ALT + F11) => insert Module => open text-file ‘Module1.txt’ => Select all and copy => paste into new module from Excel workbook.
  5. Step: Execute macro ‘prepare_worksheet’ (Reference to sapfewse.oxs will done utomatically. This require Folder-structure ENVIRON(“PROGRAMFILES”) & “SAPFRONTENDSAPguisapfewse.oxs”). If you have an different Destination please add manual.
  6. Step: Remove ‘Module1’ from macro-enabled workbook and save.
  7. Done

Usage of Excel VBA template (MM03_VBA_SAP_SCRIPTING_V1.xlsm):

This Excel template have for demonstration purposes SAP GUI Scripting integrated for getting MM03 data from ‘stor. loc. stck’-tab => ‘Qty. Unrestricted’ + “UoM’ + ‘Material description’ data.

  1. Step: Fillin ‘Materialnumber’ + ‘Company Code’ + ‘Storage location’ combination used in your system. As error handling is integrated for ‘Company Code’ + ‘Storage location’ combination you can test this as well.
  2. Step: Press button ‘Run macro ‘SAP_PROCESS’’
  3. Step: All open and Scripting-enabled SAP sessions got displayed in a Userform-Listbox
  4. Step: Select one session and press ‘Enter’ or Commandbutton
  5. Done: Script got executed and you will get data into Excel according to your input data combination (Materialnumber/CoCode/Storage location).

Important data structure information:

All data from Excel worksheet ‘SAP_PROCESS’ got stored into data-array ‘ arr_SAP_Data’ . This Array is defined with same number range as our used worksheet range. Starting from row ‘2’ up to last used row and all used columns (remember that last two columns are reserved for procedure process).

=> lngCounter is current executed row in worksheet. (lng_col +0) define column ‘1’

=> (lng_col +1) is second column

When you add or delete columns please save workbook immediately.

Feel free to use this template for your requirements by modify coding in ‘SAP_1_Process’-module. But be aware that I am not responsible for any issues, inconsistencies or other incidents which can cause by using this template. Feel free to ask if you Need any additional information. But do not expect any support for your purposes and requirements. Hope this will give you some lights how SAP GUI Scripting can make your daily tasks much smoother.

Источник

Best Practices for VBA in SAP BI Analysis for MS Excel

over the last year, I created some small applications in Analysis and thought it’s time to collect a few best practice ideas, which I experienced during development and test.

This document does not go too much into detail, since my idea is that also beginners of VBA in Analysis should be able to utilize some tips.

FYI: I worked only in 1.4.x versions so far. It might be that Analysis behaviour already changed in 2.x versions.

1) Always refresh, first!

The most important thing when doing anything in VBA related to Analysis is to refresh your datasource (DS) first … otherwise, nothing will work!

To prevent a refresh every time, you can check if the DS is already active

Dim lResult As Long

lResult = Application.Run(“SAPGetProperty”, “IsDataSourceActive“, “DS_1”)

If lResult = False Then

lResult = Application.Run(“SAPExecuteCommand”, “Refresh“, “DS_1”)

‘ Example: You can also skip the else

lResult = Application.Run(“SAPExecuteCommand”, “ShowPrompts“, “DS_1”)

2) Formulas and own columns upfront!

If you have the task to include your own Excel formula columns in your sheet, then always try to aviod putting it at the end of the Data source! Instead, put it at the beginning:

In that way you don’t have to take care about removing the columns when any drill-downs are happening and replacing them afterwards at the new end of the report. Of course you might need to adjust the formulas if they rely on certain key figure columns, but for “VLookups” it quite often saves work.

3) Find out the crosstab size

To find out the last column and row of your crosstab, you can use:

Dim lCols, lRows as Long

For this, also 1) applies! If your Datasource is not refreshed, you will not get the correct result. So if you need reliable variable contents you should store the previous “dimensions” of the crosstab in any cells on the sheet.

Especially if you “Remove Data Before Saving”. Then the crosstab is not existing and will cause you trouble if you execute a macro during Workbook initialization.

Therefore I try to avoid the checkbox “Remove Data Before Saving”.

4) Freeze the screen while macro runtime

To prevent a user is bothered with jumping through several thousand lines or several sheets, you always should freeze the screen before VBA execution and activate the screen update afterwards again. I prefer using:

‘At the very beginning

‘all the code in between…

‘At the very end

5) Fill the missing table headers for “Key and text” characteristics

Nothing more is annoying – when you want to create a PIVOT table on top of your datasource’s results – than the missing feature from the very first release: No headers on characteristics with “Key and text” display

For preventing problems 3) you should execute the macro only after 1):

Dim DS1_C, DS1_R, lResult As Long

Dim DS1 as String

DS1 = “your sheet name”

lResult = Application.Run(“SAPGetProperty”, “IsDataSourceActive”, “DS_1”)

If lResult = True Then

For i = 1 To DS1_C – 1

If Worksheets(DS1).Range(“A5”).Offset(0, i + 1) = “” Then

Worksheets(DS1).Range(“A5”).Offset(0, i + 1) = Worksheets(DS1).Range(“A5”).Offset(0, i) & “2”

In that way every blank header cell receives the text of the previous one including an attached “2”.

6) Actions after the Refresh of a Datasource: Register Callback

When you want a macro to execute everytime your datasource has been refreshed, e.g. by drill-down, execution of Variable prompt, etc. you can register a callback:

Step 1: Include this into “ThisWorkbook”

Public Sub Workbook_SAP_Initialize()

Call Application.Run(“SAPExecuteCommand”, “RegisterCallback”, “AfterRedisplay”, “Callback_AfterRedisplay”)

Step 2: In your VBA module you put all your coding between these lines:

Public Sub Callback_AfterRedisplay()

Attention: This coding is executed almost every time – even if you don’t really do anything, but just click “save”.

For that reason, you could read this note – there is a hint about improvements in your coding:

(I did not test it, yet. So I cannot give you any advice here)

7) Clear variable contents

Maybe you have the requirement to handover a long list of input characteristics to a query variable (like you would do it via the “copy from clipboard”-button), and refresh it. Unfortunately I did not found a “clear” method to remove the variable contents again.

For that reason I helped myself by setting one “default” value as key, which exists in the master data, and afterwards the user is able to simply remove it in the variable input screen:

Dim lResult As Long

lResult = Application.Run(“SAPExecuteCommand”, “Refresh”, “DS_1”)

lResult = Application.Run(“SAPExecuteCommand”, “ShowPrompts”, “DS_1”)

8) SAPGetVariable is missing

One more function is missing in my opinion… There is no SAPGetVariable() available.

That means if a user filled some variables in the prompt screen, you have to define an area in your workbook where you can get the list of all the variables, by using the formula:

Afterwards, you have to read the value of the respective cell with the right variable content:

Dim Input as Variant

Input = Sheets(“Your sheet”).Cells( , 2).Value

Finally you can use this Input to fill another variable in the second datasource, for example.

I think there are many ideas more, but for the moment it should be sufficient.

For the VBA-advanced readers, two more helpful links here:

Источник

How to access SAP using Excel VBA?

I am trying to log on to SAP. The Excel VBA code gives me a popup window confirming my information however when I submit the form it does not take me to a new SAP window.

Additionally is there a way to automate all the popup boxes asking for confirmation on my information? I want this code eventually to run at certain times of the day, and I might not be available to input any data.

2 Answers 2

This Macro will never open a SAP Window — it will create an SAP-Object within VBA where you can work with SAP-RFC-Functions. (Reading Data from SAP, Writing Data into SAP)

In your version the SAP connection will be unaccessible after «End Sub». You have to declair the Object outside the sub.

This works silent (without dialog) for me:

Since you want to «open a new SAP Window» you have to make a different approach!

At First try to open the new instance of SAP from the DOS Commandline with «sapshcut»:

If your SystemName has no Spaces (and I belive so!) then you can write it also like:

When this call works with your credentials, then you can transfer it to Excel like this:

You could also add a transaction by adding «-command=your_tcode» to the String.

If your have spaces in the parameters and you could only start it with -system=»System Test Environment» from the Commanline, you will have to escape this in Excel with -system=»»»System Test Environment»»» (!)

Источник

SAP Intelligent RPA: Reading Data from Excel using VBA Excel reference properties

This is to ease the reading of excel files which could have unknown number of rows to be read.

In this post I will show you how to read an Excel file with unknown number of rows using VBA Excel reference properties and custom scripts

What will you learn in this blog:

  • Basics of excel reading
  • Reading excel file using custom scripts
  • VBA Excel reference properties that can make Excel reading simple
  • Reading unknown number of rows without loops in workflow

Brief on Excel VBA reference that would be used to get all the Values without any Loops:

  • Excel VBA Object model has Application object which refers to the entire Microsoft Excel application
    • Application object has property ActiveSheet that returns the active Worksheet in the active excel
  • WorkSheet object , in Excel VBA objects, which represents the Worksheet of the excel
    • WorkSheet object has property UsedRange that returns the Range on the Worksheet that has been used or filled
  • Range object represents one cell or block of cells
    • Address property of Range, provides the representation of range as string

Steps to follow:

  1. Create a project;
  2. Create a new Workflow;
  3. Import Excel Library Scripts;
  4. Designing Workflow with Custom Scripts
  5. Display range address and random cell value

Prerequisites:

  • Desktop Studio
  • Microsoft office

Instructions:

1. Create a project

Open Desktop Studio and create a new project from File menu. Give it a name

2. Create a new workflow

Go to Workflow perspective , right click on Global and add new workflow give it a name.

3.Import Excel Library Scripts

Whenever you create a project, its framework includes most of the Libraries that would be useful for creating the workflows. Though you can drag and drop or use the Excel Lib function in your workflows, until you include the Excel Library workflow would run into errors during compilation and execution.

To include excel library,

go to edit project in the file menu, navigate to Libraries and select Excel integration

Or go to Scripts, right click on Global, click Include Library Script and select Excel Integration

4. Designing Workflow with Custom Scripts

  • Add Activity of Initialize Excel which initializes the Excel library and mode parameters
    • Mark the Initialization as start node with a right click and selecting Set as Start Node

  • Next activity is to open the excel file, we add open existing Excel file ,from the activity list functions of Excel Lib. Filename must be a string and if path has been provided the separator would be \ between the folders.

  • In case the workbook opened has multiple worksheets, we need to activate the sheet to be read, use Activate worksheet activity. If workbook has only one worksheet, it is optional activity. As the workbook used has multiple sheets, the following activating function has been added.

  • Add Custom activity, to read the data from the sheet activated

  • Once we generate the build for workflow created, we would be able to edit the custom activity to include the custom script. Click on the build to generate the script for the workflow.

  • Go to Scripts -> workflow script -> Custom step to add the code to extract data using VBA properties

  • Go to Scripts and right click to add custom library script

    • Define the function getContents that has been used in Custom Step of the Workflow
      • ctx.excel.application.getObject is available in Excel Library which fetches the Excel object. For more information refer to the documentation of the library.
      • Application.ActiveSheet is Excel VBA property which fetches the active Worksheet
      • UsedRange is the property of worksheet that returns the Range Object
      • Address property of the Range provides the address of the range object as string . Ex: ‘$A$1:$B$3’
      • ctx.excel.sheet.getValuesFromRangeDefinition takes the range definition as string. For more information refer to the documentation of the library

5. Display Range address and Random Cell Value

  • ctx.log has been used to write the property data to the logs for validation
  • Log will be written with the Active sheet Name , Range Address and cell value at (1,1) position

Following file has been used,:

  • File has two sheets with name ‘header’ and ‘item’.
  • Active sheet would be ‘header’
  • Range to be read would be “A1:H5”
  • Cell Value at (1,1) position would be ‘A’

Following is the context log

As Excel VBA objects and properties used in Library of SAP IRPA, there would be warnings but the properties would be available during runtime.

Conclusion

Using Excel VBA Object properties in SAP Intelligent RPA would give the bot less time to read the whole data without using explicit loops. You can reuse the custom library to read the Excel for any dimensions

Источник

Список литературы по программированию в SAP Вы наверно и так уже видели в топе форума.

Если судить по первой же Вашей фразе о необходимости выгружать из SAP некие экономические данные, то это может означать объём работ на целый проект стоимостью несколько миллионов, или наоборот плёвым делом для специалиста SAP. Опишите подробней, какие задачи, что за экономические данные, кто пользователи?

Ключевым моментом в решении подобных проблем является знание SAP в разрезе решаемой экономической задачи, а знание SQL, VBA или даже ABAP вторично.
Вероятней всего наиболее правильно Ваше предположение о необходимости что-то делать на стороне SAP. Причём вообще всё! Т.е. формирование нужного пользователю отчёта полностью на стороне SAP и отображение его в необходимой форме — Excel, PDF или другой. Возможно и разработка на ABAP не потребуется, т.к. могут подойти стандартные отчёты, либо достаточно воспользоваться генератором отчётов, например, SAP-Query.
Для этого вам лучше привлечь опытного консультанта, например, фрилансера, чтобы он рассмотрел ваши конкретные потребности (выгрузка в Excel не задача, а уже решение какой-то другой задачи) и возможно частично решил их, а частично потребуется разработка. Для разработки можно дополнительно привлечь ABAP-ера, конечно если не найдёте универсала «два в одном». Попутно им можно было бы поручить и Ваше обучение. По моему убеждению такой подход эффективнее и дешевле для вашей компании, чем Ваше самообучение.

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:Temp"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording.
Click the customize local layout button, it probably looks a bit like this:
Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

Кто-нибудь знает, как использовать VBA для извлечения данных из SAP Netweaver?

У меня есть несколько ежедневных отчетов, которые требуют экспорта данных из SAP в Excel и форматирования их в отчет. Я уже написал рабочие макросы VBA, которые делают форматирование. Я должен вручную извлекать данные и запускать каждый макрос отчета отдельно. Так много времени можно было бы сохранить, если бы мой макрос мог просто перейти в SAP, захватить данные для отчета №1, отформатировать его, захватить данные для отчета № 2 и т.д.

Я работаю с SAP NetWeaver (выпуск 730, версия 7300.1.3.1079). Отчеты представляют собой таблицы и диаграммы сводных таблиц Excel.

Спасибо!

4b9b3361

Ответ 1

Все зависит от того, какой доступ к вашей системе SAP вы используете. Программа ABAP, которая экспортирует данные и/или RFC, которые ваш макрос может вызывать для непосредственного получения данных или создания файла SAP, вероятно, лучше всего.

Однако, как правило, люди, которые ищут такой ответ, ищут немедленное решение, которое не требует, чтобы их ИТ-отдел потратил месяцы на настройку своей системы SAP.

В этом случае вы, вероятно, захотите использовать SAP GUI Scripting. Сценарии SAP GUI позволяют автоматизировать графический интерфейс Windows SAP так же, как автоматизировать Excel. Фактически вы можете вызвать SAP GUI непосредственно из макроса Excel. Подробнее читайте здесь здесь. В SAP GUI есть инструмент для записи макросов, как это делает Excel. Он записывает макросы в VBScript, который почти идентичен Excel VBA и обычно может быть скопирован и вставлен непосредственно в макрос Excel.

Пример кода

Вот простой пример, основанный на системе SAP, к которой у меня есть доступ.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:Temp"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Запись

Чтобы найти имена таких элементов, как wnd[1]/tbar[0]/btn[0], вы можете использовать запись script.
Нажмите кнопку «Настройка локального макета», это, вероятно, выглядит примерно так:
Customize Local Layout
Затем найдите пункт меню script Запись и воспроизведение.
Script Recording and Playback
В этом случае кнопка More позволяет вам видеть/изменять файл, в который записывается VB script. Формат вывода немного грязный, он записывает такие вещи, как выбор текста, щелчок внутри текстового поля и т.д.

Изменить: ранняя и поздняя привязка

Предоставленный script должен работать, если он скопирован непосредственно в макрос VBA. Он использует последнее связывание, строка Set SapGuiAuto = GetObject("SAPGUI") определяет объект SapGuiAuto.

Если вы хотите использовать раннее связывание, чтобы ваш редактор VBA мог показывать свойства и методы объектов, которые вы используете, вам нужно добавить ссылку на sapfewse.ocx в папку установки GUI SAP.

Like this post? Please share to your friends:
  • Sap pdf to word
  • Sap excel to table
  • Sap and microsoft excel
  • Sap analysis для microsoft excel это
  • Sap analysis for microsoft excel что это