首页 > 解决方案 > 从 VBA 运行多个 Matlab 脚本

问题描述

经过整整两个晚上在这里寻找答案和其他平台以运行多个 Matlab 脚本(一个接一个),这是我能想到的最好的方法是结合不同的解决方案。它工作正常,但我对它不满意,因为它不是那么理想。如果有人有更好的解决方法(我的大脑已经死了),我将不胜感激,在此先感谢您。

背景故事(我正在尝试从 VBA 运行 6 个 Matlab 脚本,为了避免 open.excel 碰撞错误,我必须一个接一个地运行。由于 Matlab shell 命令没有返回选项,我决定创建一个文本文件,每个 Matlab 脚本在完成后会输出其名称,稍后将由 VBA 脚本循环读取,直到匹配,然后运行下一个 Matlab 脚本。

Sub RunModels()
Call GlobaleVariable
Dim run As Double
Dim strFilename As String: strFilename = "C:\Users\" + Environ("username") + "" & Application.PathSeparator & MainPath & "\" & "MTLB_Timer.txt"
Dim iFile As Integer: iFile = FreeFile
Dim MyTxtFile() As String
Dim Models
    Models = Array("Macro_cyc", "SEI", "FinancialValuation", "FLO_2021", "SentimentMain", "FGMain")
Dim path
    path = Array("Macro_Indicator", "Monetary_Uncertainty", "Financial_Valuation", "FLO", "Sentiment", "Fear_Greed")

Open "C:\Users\" + Environ("username") + "" & Application.PathSeparator & MainPath & "\" & "MTLB_Timer.txt" For Output As #1: Close #1


Open strFilename For Input As #iFile
strFileContent = Input(LOF(iFile), iFile)
Close #iFile
MyTxtFile = Split(strFileContent, vbLf)

    'Loop through models and run
    For i = LBound(Models) To UBound(Models)
    If Not i = 0 Then
            Do Until MyTxtFile(i - 1) <> Models(i - 1)
                Filetorun = "C:\Users\" + Environ("username") + "" & Application.PathSeparator & MainPath & "\" & path(i) & "\" & Models(i) & ".mlx"
                mc = "matlab -nodisplay -nosplash -nodesktop -r "" run('" & Filetorun & "');exit;"" "
                Shell (mc)
                Do Until UBound(MyTxtFile) = i
                    Open strFilename For Input As #iFile
                    strFileContent = Input(LOF(iFile), iFile)
                    Close #iFile
                    MyTxtFile = Split(strFileContent, vbLf)
                        Application.Wait (Now + TimeValue("0:00:5"))
                Loop
                If MyTxtFile(i) = Models(i) Then Exit Do
            Loop
    Else
    Filetorun = "C:\Users\" + Environ("username") + "" & Application.PathSeparator & MainPath & "\" & path(i) & "\" & Models(i) & ".mlx"
    mc = "matlab -nodisplay -nosplash -nodesktop -r "" run('" & Filetorun & "');exit;"" "
    Shell (mc)
    End If
    Do Until UBound(MyTxtFile) = i
                    Open strFilename For Input As #iFile
                    strFileContent = Input(LOF(iFile), iFile)
                    Close #iFile
                    MyTxtFile = Split(strFileContent, vbLf)
                        Application.Wait (Now + TimeValue("0:00:5"))
    Loop
    Next


End Sub
   

标签: vbamatlabshellloops

解决方案


推荐阅读