Excel宏:浏览Excel文件并使用其工作表数据

时间:2012-09-12 03:42:23

标签: vba excel-vba excel

我写了一个这样的脚本:

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

    Call main_function
End Sub

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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

猜猜你只想将用户限制为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

答案 1 :(得分:1)

继续@Larry的回答,你可以使用以下模块,如果需要通过CodeName引用工作表,或者如果想通过工作表名称引用你可以使用工作表选项,感谢MVP-JuanPabloGonzá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-JuanPabloGonzález解决方案的链接: https://www.mrexcel.com/forum/excel-questions/58845-codename-selecting-sheets-through-visual-basic-applications.html

希望有所帮助。