设置找到/打开的工作簿

时间:2019-02-16 10:04:53

标签: excel vba

问题:我无法设置找到/打开的工作簿

代码:以下是我的代码。我的错误发生在第Set wkbTemp = wkbTempStr行,错误为Type Mismatch

我尝试了一些变体,进行了一些搜索,但出现空白。.任何帮助将不胜感激。

Sub Test_wkb()

    Dim wbcount As Integer
    wbcount = Workbooks.Count

    For i = 1 To wbcount
        wkb = Workbooks(i).Path & "\" & Workbooks(i).Name
    Debug.Print wkb
    Next

    Dim wkbTempStr As String
    Dim wkbTemp As Workbook
    Dim wksTemp As Worksheet

    wkbTempStr = "C:\Users\JohnDoe\Desktop\Consolidate Macro.xlsm"

    Set wkbTemp = wkbTempStr
    Set wksTemp = wkbTemp.Sheets("Pay")

    'just seeing if code works below
    wksTemp.Range("I18") = "This works"

End Sub

1 个答案:

答案 0 :(得分:1)

打开/关闭工作簿

引用打开的工作簿时,必须使用其名称,例如文件名。 “ Consolidate Macro.xlsm”。如果未打开,则必须使用完整路径打开,如果该文件不在当前目录中(始终是最佳目录)。

代码

Option Explicit

Sub Test_wkb()

    Dim wkb As String
    Dim wbcount As Long
    Dim i As Long

    wbcount = Workbooks.Count

    For i = 1 To wbcount
        wkb = Workbooks(i).Path & "\" & Workbooks(i).Name
        Debug.Print wkb
    Next

    Dim wkbTempStr As String
    Dim wkbTemp As Workbook
    Dim wksTemp As Worksheet

    wkbTempStr = "C:\Users\JohnDoe\Desktop\Consolidate Macro.xlsm"

    ' If you want to suppress the message alerting that the workbook is already 
    ' open, uncomment the two "Application ..." lines.
    'Application.DisplayAlerts = False
    Set wkbTemp = Workbooks.Open(wkbTempStr)
    'Application.DisplayAlerts = True
    Set wksTemp = wkbTemp.Sheets("Pay")

    'just seeing if code works below
    wksTemp.Range("I18") = "This works"

End Sub

使用文件名(Workbook.Name),可以循环浏览打开的工作簿并检查它是否打开。如果不是,则使用路径将其打开。