Running code from VBA to VBScript back to VBA

后端 未结 2 381
别那么骄傲
别那么骄傲 2021-01-20 23:01

I\'m trying to figure out a way to call a VBScript function using vba in Excel, and then pass a value back to excel-vba. See below

VBA

相关标签:
2条回答
  • 2021-01-20 23:42

    Try syntax like:

    Sub Test()
        Shell "cscript c:\TestFolder\sample.vbs", vbNormalFocus
    End Sub
    
    0 讨论(0)
  • 2021-01-20 23:46

    Ok, I feel a litte dirty :)

    This code has two key parts:

    • the vbs Uses GetObject and the full host workbook path to re-attach to the file containing the VBA that called the VBS
    • the VBS adds a value to a specific worksheet in the host VBA file to trigger the Worksheet_Change event to fire, running VBA with the string passed from the VBS.

    Step 1: Regular Excel code module

    Sub VBA_to_VBS_to_VBA()
    Shell "wscript c:\temp\myvbs.vbs", vbNormalFocus
    End Sub
    

    Step 2: myvbs

    Dim xlApp
    Dim xlSht
    On Error Resume Next
    Set xlApp = GetObject("c:\temp\mybook.xlsx").Application
    Set xlSht = xlApp.Sheets("vbs sheet")
    On Error GoTo 0
    If Not xlSht Is Nothing Then
    xlSht.Range("A1").Value = "hello world"
    Else
    wscript.echo "sheet not found"
    End If
    

    Step 3: Sheet code for vbs sheet in your Excel File

    Private Sub Worksheet_Change(ByVal Target As Range)
    MsgBox [a1].Value, vbCritical, "VBS insertion"
    End Sub
    
    0 讨论(0)
提交回复
热议问题