Excel VBA代码打开文件

时间:2012-04-13 17:31:00

标签: excel vba

我创建了一个宏按钮,用于从excel生产工作表中打开我的日常文件,其中包含特定文件的所有宏按钮。

我所有文件的格式通常都是相同的:

  1. Businese单位名称:YMCA
  2. 年:2012
  3. 月:4月
  4. 周:第2周
  5. Day:12
  6. 文件名:YMC模板041212.xlsm
  7. 我遇到了最后一个excel文件扩展名的问题。 如何添加MyDaily模板和MyDateProd以及.xlsm。 我有这个-J:..... \& myDailyTemplate& myDateProd.xlsm“)请参阅下面的整个文件路径名。

    Sub Open_DailyProd()
    
        Dim myFolderYear As String
        Dim myFolderMonth As String
        Dim myFolderWeek As String
        Dim myFolderDaily As String
        Dim myDateProd As String
        Dim myBusinessUnit As String
        Dim myDailyTemplate As String
    
        myBusinessUnit = Sheet1.Cells(32, 2)
        myFolderYear = Sheet1.Cells(11, 2)
        myFolderMonth = Sheet1.Cells(12, 2)
        myFolderWeek = Sheet1.Cells(13, 2)
        myFolderDaily = Sheet1.Cells(14, 2)
        myDateProd = Sheet1.Cells(15, 2)
        myDailyTemplate = Sheet1.Cells(6, 5)
    
        Application.Workbooks.Open ("J:\IAS\3CMC05HA01\IAC Clients\myBusinessUnit\myFolderYear\myFolderMonth\myFolderWeek\myFolderDaily\& myDailyTemplate & myDateProd.xlsm")
    
    End Sub
    

1 个答案:

答案 0 :(得分:5)

Excel正在寻找一个名为的文件: "J:\IAS\3CMC05HA01\IAC Clients\myBusinessUnit\myFolderYear\myFolderMonth\myFolderWeek\myFolderDaily\& myDailyTemplate & myDateProd.xlsm"

因为这是引号中包含的内容,但是从您的代码中,您似乎有许多变量属于此字符串,您需要将它们从引号中取出并将它们连接在一起。尝试这样的事情:

"J:\IAS\3CMC05HA01\IAC Clients\" & myBusinessUnit & "\" & myFolderYear _
& "\" & myFolderMonth & "\" & myFolderWeek & "\" & myFolderDaily & _
"\" & myDailyTemplate & myDateProd & ".xlsm"

我添加了延续_以使其在屏幕上更具可读性,但没有必要,如果您愿意,可以将所有内容放在一行。

除非您在其他地方需要所有myBusinessUnitmyFolderYear等变量,否则我会考虑在某种数组中执行此操作,然后执行Join函数来连接所有内容。我个人认为,这更易于维护,更容易在文件夹结构中查看层次结构,而不是查看非常长的字符串并尝试查找路径的哪个部分是错误的。

Sub Open_DailyProd()

    Dim pathParts(1 To 10) As String
    Dim path As String

    pathParts(1) = "J:"
    pathParts(2) = "IAS"
    pathParts(3) = "3CMC05HA01"
    pathParts(4) = "IAC Clients"
    pathParts(5) = Sheet1.Cells(32, 2)
    pathParts(6) = Sheet1.Cells(11, 2)
    pathParts(7) = Sheet1.Cells(12, 2)
    pathParts(8) = Sheet1.Cells(13, 2)
    pathParts(9) = Sheet1.Cells(14, 2)
    pathParts(10) = Sheet1.Cells(6, 5) & Sheet1.Cells(15, 2) & ".xlsm"

    path = Join(pathParts, "\")

    Application.Workbooks.Open (path)

End Sub