3

我写了一个这样的脚本:

Sub Button_Click()
    objFile = Application.GetOpenFilename(fileFilter:="All Files (* . *) , * . * ") ' choose load path
    .....

    Call main_function
End Sub

这是一个 Excel 宏按钮的脚本,用于让用户浏览文件。实际上,我想用它来加载一个 Excel 文件并在main_function(当前的 excel)中使用该 Excel 文件的数据。

我怎样才能做到这一点?

4

2 回答 2

4

猜想您只想将用户限制为 Excel,所以我为您修改了过滤器

Dim pathString As String
Dim resultWorkbook As Workbook
Dim found As Boolean
pathString = Application.GetOpenFilename(fileFilter:="All Files (* . xl*) , *.xl* ")

' check if it's already opened
For Each wb In Workbooks
    If InStr(pathString, wb.Name) > 0 Then
        Set resultWorkbook = wb
        found = True
        Exit For
    End If
Next wb

If Not found Then
    Set resultWorkbook = Workbooks.Open(pathString)
End If

' then you can use resultWorkbook as a reference to the Excel Workbook Object
于 2012-09-24T05:19:24.923 回答
3

继续@Larry 的回答,如果需要通过 CodeName 引用工作表,您可以使用以下模块,或者如果想通过工作表名称引用,您可以使用工作表选项,感谢 MVP-Juan Pablo González 在另一个博客上的回答:

'Strating sub procedure to write VBA Code to Open an only Excel 2007 macro Files using File Dialog Box
Sub Browse_File()
Dim strFileToOpen As String
Dim Wbk_WeeklyTemplate As Workbook
Dim Tgt_ShtNm As String
Dim Src_ShtNm As String

'Choosing an Excel File using File dialog Box and capturing the file path in the variable
strFileToOpen = Application.GetOpenFilename(Title:="Please select the file to open", FileFilter:="Excel Files *.xlsm (*.xlsm),")

'Checking if file is selected
If strFileToOpen = "False" Then
    MsgBox "No file selected.", vbExclamation, "Sorry!"
    Exit Sub
Else
    Set Wbk_WeeklyTemplate = Workbooks.Open(strFileToOpen)
End If

''Refer sheet by Sheet CodeName
Src_ShtNm = SheetName(Wbk_WeeklyTemplate, "sheetCodeName")
Tgt_ShtNm = SheetName(ThisWorkbook, "sheetCodeName")

Wbk_WeeklyTemplate.Sheets(Src_ShtNm).Range("N15:X18").Copy
ThisWorkbook.Sheets(Tgt_ShtNm).Range("A1").PasteSpecial xlPasteValues

End Sub


''The function SheetName returns the actual name of the sheet by passing sheet code name
Function SheetName(Wb As Workbook, CodeName As String) As String
    SheetName = Wb.VBProject.VBComponents(CodeName).Properties("Name").Value
End Function

MVP-Juan Pablo González 解决方案的链接: https ://www.mrexcel.com/forum/excel-questions/58845-codename-selecting-sheets-through-visual-basic-applications.html

希望有帮助。

于 2017-01-24T06:39:50.107 回答