cancel
Showing results for 
Search instead for 
Did you mean: 

Copy and paste data from SAP to Excel with VBA

jay_jung
Explorer
0 Kudos
3,681

Hi, All

I'm newer to VBA and SAP

I'm trying to make a macro with VBA, I need a help.

I want to copy a specific data from SAP in T-code ZVIRS and paste it to Excel, but I couldn't make it.

I want to copy a item data in ZVIRS code.

Here is my VBA code.

Is anyone who can help me?

Please and thanks in advance.

Sub SAP_OpenSessionFromLogon()

Dim SapGui

Dim Applic

Dim connection

Dim session

Dim WSHShell

Shell "C:\Program Files (x86)\SAP\FrontEnd\SAPgui\saplogon.exe", vbNormalFocus

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 Applic = SapGui.GetScriptingEngine

Set connection = Applic.OpenConnection("SAP Production R3", True)

Set session = connection.Children(0)

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

session.findById("wnd[0]/usr/txtRSYST-MANDT").Text = "050"

session.findById("wnd[0]/usr/txtRSYST-BNAME").Text = "UserID"

session.findById("wnd[0]/usr/pwdRSYST-BCODE").Text = "Mypassword"

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

session.SendCommand ("/nZVIRS")

Dim materialNo As String

Dim plant As String

materialNo = ThisWorkbook.Sheets("Sheet1").Range("A1").Value

plant = "7022"

session.findById("wnd[0]/usr/ctxtP_MATNR").Text = materialNo

session.findById("wnd[0]/usr/ctxtP_WERKS").Text = plant

session.findById("wnd[0]/tbar[1]/btn[8]").press

session.findById("wnd[0]/usr/tblSAPMZVIS_TCNTRL_OUT/txtZVSIS-ZPOSNR[14,0]").SetFocus

session.findById("wnd[0]/usr/tblSAPMZVIS_TCNTRL_OUT/txtZVSIS-ZPOSNR[14,0]").caretPosition = 3

"From here, I don't know how can I make a code for copy and paste from SAP to Excel"

sht = "Sheet1"

With sht

.Cells(2, 1).Value = session.findById("wnd[0]/usr/tblSAPMZVIS_TCNTRL_OUT/txtZVSIS-ZPOSNR[14,0]").SetFocus

End With

Set sht = Nothing

MsgBox "Wating"

Set session = Nothing

connection.CloseSession ("ses[0]")

Set connection = Nothing

Set SAP = Nothing

End Sub

Accepted Solutions (0)

Answers (0)