如何在不打开工作簿的情况下引用工作簿

我想打开一个新工作簿,并在其中运行一些宏,最后将结果粘贴到新工作簿中。

我尝试了其他方法来引用其他工作簿路径,因为我需要内部数据,但是,我无法正确执行此操作。下面是我的编码:

Sub stepTen()
    Dim wbLinelist As String,wsLinelist As String

    wbLlinelist = "C:\Users\abc\Excel\trial\ppp.xlsx"
    wsLinelist = "Sheet1"

    Dim llStyle As Long
    Dim colllStyle,As String

    With Workbooks(wbLlinelist).Worksheets(wsLinelist)
        llStyle = Application.Match("fire",.Rows(1),0)
        colllStyle = Split(Cells(1,llStyle).Address,"$")(1)
    End With
End Sub
hhudeng 回答:如何在不打开工作簿的情况下引用工作簿

  1. Dim colllStyle,As String是无效的语法,请删除逗号。

  2. Cells(1,llStyle).Address中未指定Cells对象应位于哪个工作簿和工作表中。如果要使用.Cells(…)语句,则应该以点With开头,或者必须指定工作簿/工作表。

  3. 如果Application.Match("fire",.Rows(1),0)不匹配,则返回错误。因此,您必须使用IsError function检查它是否匹配或错误:

    If Not IsError(llStyle) Then
        'split
    Else
        'error message
    End If
    
  4. 最后,您的主要问题是无法在"C:\Users\abc\Excel\trial\ppp.xlsx"中使用完整路径Workbooks(wbLlinelist)。您必须先使用Workbooks.Open method打开工作簿,然后才能访问它。

    Dim MyOpenWb As Workbook
    Set MyOpenWb = Application.Workbooks.Open(FileName:=wbLlinelist) 'you might want to open it read only and set the parameter ReadOnly:=True
    
    With MyOpenWb.Worksheets(wsLinelist)
        'your code
    End With
    
  5. 别忘了最后关闭工作簿:

    MyOpenWb.Close SaveChanges:=False
    
本文链接:https://www.f2er.com/3155311.html

大家都在问