Excel VBA 使用命名范围从封闭的工作簿获取数据

Excel VBA 使用命名范围从封闭的工作簿获取数据

我正在使用找到的代码这里(复制如下)从关闭的工作簿中提取数据。

我想要实现的是使用命名范围在目标源中,而不是硬编码地址。因此在第 22 行,它定义了Address = Cells(Row, Column).Address我希望能够只给它一个命名范围(存在于目标中)......但这似乎使得该getData()功能不再起作用。

Option Explicit 

 'you can extract data from a closed file by using an
 'XLM macro. Credit for this technique goes to John
 'Walkenback > http://j-walk.com/ss/excel/tips/tip82.htm

Sub GetDataDemo() 

  Dim FilePath$, Row&, Column&, Address$ 

   'change constants & FilePath below to suit
   '***************************************
  Const FileName$ = "Book1.xls" 
  Const SheetName$ = "Sheet1" 
  Const NumRows& = 10 
  Const NumColumns& = 10 
  FilePath = ActiveWorkbook.Path & "\" 
   '***************************************

  DoEvents 
  Application.ScreenUpdating = False 
  If Dir(FilePath & FileName) = Empty Then 
      MsgBox "The file " & FileName & " was not found", , "File Doesn't Exist" 
      Exit Sub 
  End If 
  For Row = 1 To NumRows 
      For Column = 1 To NumColumns 
          Address = Cells(Row, Column).Address 
          Cells(Row, Column) = GetData(FilePath, FileName, SheetName, Address) 
          Columns.AutoFit 
      Next Column 
  Next Row 
  ActiveWindow.DisplayZeros = False 
End Sub 


Private Function GetData(Path, File, Sheet, Address) 
  Dim Data$ 
  Data = "'" & Path & "[" & File & "]" & Sheet & "'!" & _ 
  Range(Address).Range("A1").Address(, , xlR1C1) 
  GetData = ExecuteExcel4Macro(Data) 
End Function 

答案1

好的,我找到了答案......似乎我在发布之前没有充分地使用 Google,所以很抱歉。

在上面的代码中,将以下内容Private Function GetData()替换:

Data = "'" & Path & "[" & File & "]" & Sheet & "'!" & _ 
       Range(Address).Range("A1").Address(, , xlR1C1)

和:

Data = "'" & Path & File & "'!" & Address

可以Address设置命名范围字符串值……一切正常。

相关内容