我想用其他工作簿中的值填充一些单元格。为了实现这一点,我编写了一个函数,它将一个人的名字作为参数,这将是要打开和读取信息的文件的名称。
为了简化,我们假设只有一个人。
调用该函数的工作表位于
C:\Dados\People
我想要阅读的文件位于
C:\Dados\People\Projects
这是我到目前为止的代码,只是简单地回显第一个工作表中存储的单元格的值:
Public Function TipoProjeto(name As String) As String
Dim shAux As Worksheet
shAux = Workbooks.Open(Filename:="C:\Dados\People\Projects\person1.xlsx").Sheets(sheet1)
MsgBox shAux.Range("B2").Value
TipoProjeto = "test"
End Function
我为MsgBox指令设置了一个断点,但我无法通过open指令。我能错过什么?
答案 0 :(得分:1)
在开头使用Workbook对象而不是工作表对象。 以下将起作用:
Public Function TipoProjeto() As String
Dim location As String
location = "C:\Dados\People\Projects\person1.xlsx"
Dim wkb As Workbook
Set wkb = Workbooks.Open(location)
Dim sht As Worksheet
Set sht = wkb.sheets("Sheet1") 'Use set sht = wkb.sheet1 only if the sheet has been named this in the project explorer
MsgBox sht.Range("B2").Value
TipoProjeto = "test"
End Function