2015-06-10 76 views
0

我已经写了一些Word VBA,它接收Excel文件并更新Word文件中的标签(ActiveX控件)。这个Excel文件唯一的将会改变每个月的路径和文件名。如何添加“打开文件”对话框,以便用户选择要使用的Excel文件,而不是每月编辑2个变量?打开文件对话框获取Excel

这是我现在有:

Sub Update() 
    Dim objExcel As New Excel.Application 
    Dim exWb As Excel.Workbook 

    PathWork = "C:\My Documents\2015-05 Report\" 
    CalcFile = "May2015-data.xlsx" 

    Set exWb=objExcel.Workbooks.Open(FileName:=PathWork & CalcFile) 
    ThisDocument.date.Caption=exWb.Sheets("Data").Cells(1,1) 
End Sub 

回答

2

这是一个简化的宏,它允许用户只选择启用宏的Excels。我无法评论以前的答案,因为我没有赢得足够的声望来评论答案。请介意一下。

Public Sub GetCaptionFromExcel() 
    Dim objExcel As New Excel.Application, exWb As Workbook 
    With Application.FileDialog(msoFileDialogFilePicker) 
     .Title = "Select Macro-Enabled Excel Files" 
     .Filters.Add "Macro-Enabled Excel Files", "*.xlsm", 1 
     If .Show <> -1 Then Exit Sub 

     Set exWb = objExcel.Workbooks.Open(.SelectedItems(1)) 
     '*** Use the values from excel here*** 
     MsgBox exWb.Sheets("Data").Cells(1, 1) 
     '*** Close the opened Excel file 
     exWb.Close 
    End With 
End Sub 
+0

谢谢,这工作完美! – wongnog

+0

随时欢迎。 :-) –

0

你可以尝试这样的事情

Dialogbox

With Dialogs(wdDialogFileOpen) 
    If .Display Then 
     If .Name <> "" Then 
      Set exWb = Workbooks.Open(.Name) 
      sPath = exWb.Path 
     End If 
    Else 
     MsgBox "No file selected" 
    End If 
End With 

完全CODE应该像更换PathWorkCalcFile

Option Explicit 

Sub Update() 
    Dim objExcel As New Excel.Application 
    Dim exWb As Excel.Workbook 
    Dim sPath As String 

    '// Dialog box here to select excel file 
    With Dialogs(wdDialogFileOpen) 
     If .Display Then 
      If .Name <> "" Then 
       Set exWb = Workbooks.Open(.Name) 
       sPath = exWb.Path 
      End If 
      Set exWb = objExcel.Workbooks.Open(FileName:=sPath) 
      ActiveDocument.Date.Caption = exWb.Sheets("Data").Cells(1, 1) 
     Else 
      MsgBox "No file selected" 
     End If 
    End With 
    Set objExcel = Nothing 
    Set exWb = Nothing 
End Sub 
+0

谢谢奥马尔!但是,我将如何将它与我所展示的代码进行整合?这是我的主要Word VBA宏,除了有许多行.Caption链接到我的Excel对象exWb – wongnog

+0

@wongnog看到更新的答案,我还没有测试,但我会尽快得到一分钟。 – 0m3r

+0

感谢奥马尔,我认为它快到了!你的代码虽然期待一个Word文档,但不喜欢当我尝试并通过一个Excel文件时(出现运行时错误'5792':该文件似乎已损坏)。你能帮我过滤一下启用宏的Excel文件(.xlsm)吗?谢谢! – wongnog