使用VB6

时间:2015-06-24 08:34:47

标签: excel vb6

我正在尝试使用vb6访问存储在excel工作簿中的宏。我打开一个包含几张纸的工作簿。其中一些有宏。能够列出所有宏(带有名称)并让用户从列表中选取一个或多个宏并运行它们的方法是什么?

类似地,我希望能够列出按钮(放在工作表上的命令按钮)而不是内置的工具栏按钮,并最终点击它,再次为用户提供按钮的名称(或最好的标题)。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

以下是How to retrieve the names of macros from an Excel workbook by using Visual Basic 6.0中的一些代码,用于将工作表中的宏列表(示例中为c:\ abc.xls)加载到名为List1的列表框中:

Private Sub LoadMacrosList()
    ' Declare variables to access the Excel workbook.
    Dim objXLApp As Excel.Application
    Dim objXLWorkbooks As Excel.Workbooks
    Dim objXLABC As Excel.Workbook

    ' Declare variables to access the macros in the workbook.
    Dim objProject As VBIDE.VBProject
    Dim objComponent As VBIDE.VBComponent
    Dim objCode As VBIDE.CodeModule

    ' Declare other miscellaneous variables.
    Dim iLine As Integer
    Dim sProcName As String
    Dim pk As vbext_ProcKind

    ' Open Excel, and open the workbook.
    Set objXLApp = New Excel.Application
    Set objXLWorkbooks = objXLApp.Workbooks    
    Set objXLABC = objXLWorkbooks.Open("C:\ABC.XLS")

    ' Empty the list box.
    List1.Clear

    ' Get the project details in the workbook.
    Set objProject = objXLABC.VBProject

    ' Iterate through each component in the project.
    For Each objComponent In objProject.VBComponents

        ' Find the code module for the project.
        Set objCode = objComponent.CodeModule

        ' Scan through the code module, looking for procedures.
        iLine = 1
        Do While iLine < objCode.CountOfLines
            sProcName = objCode.ProcOfLine(iLine, pk)
            If sProcName <> "" Then
                ' Found a procedure. Display its details, and then skip 
                ' to the end of the procedure.
                List1.AddItem objComponent.Name & vbTab & sProcName
                iLine = iLine + objCode.ProcCountLines(sProcName, pk)
            Else
                ' This line has no procedure, so go to the next line.
                iLine = iLine + 1
            End If
        Loop
        Set objCode = Nothing
        Set objComponent = Nothing
    Next

    Set objProject = Nothing

    ' Clean up and exit.
    objXLABC.Close
    objXLApp.Quit
End Sub

这里有一些代码可以运行其中一个宏(source):

Private Sub RunMacro(string macroName)
    'create and object (Excel SpreadSheet) 
    Dim oXL As Object 
    Set oXL = CreateObject("Excel.Application") 

    ' Open the workbook that contains the macro to run. 
    oXL.Workbooks.open "C:\ABC.XLS" 
    ' 
    'as object opens invisible, make visible if needed, if not omit 
    'the line oXL.visible=true 
    ' 
    oXL.Visible = True 
    ' 
    ' Run the macro. 
    oXL.Application.Run "abc.xls!" & macroName
    ' 
    ' Quit Microsoft Excel. 
    oXL.Quit 
    ' 
    ' Free the object from memory. 
    Set oXL = Nothing 
End Sub

您需要做一些额外的工作,您也应该能够找到命令按钮。如果您正在寻找更多,那么更为现代的编程语言可能会更合适。