我花了很多时间试图解决这个问题并希望得到一些帮助。
我想根据包含文件路径的单元格值(例如A1)打开一个已关闭的工作簿,并将其打开到与另一个单元格匹配的工作表(例如A2)。
例如A1 = C:\ User \ TEST.xls 和A2 = Sheet3
我想要一个打开C:\ User [TEST.xls] Sheet3的按钮 这是我到目前为止所得到的:
Sub OpenSesame()
Dim ClosedBook As Workbook
Set ClosedBook = Workbooks.Open(Filename:=Application.Range("ClosedBookFile").Value)
'ClosedBookFile is a named cell
ClosedBook.Sheets(*DYNAMIC CELL VALUE*).Activate
Range("A1").Select
End Sub
我可以用什么代替动态单元格值来打开特定的工作表,还是我咆哮错误的树? 谢谢你的帮助
答案 0 :(得分:0)
将工作表的名称作为变量引用并稍后引用它可能是个好主意。像这样:
Option Explicit
Sub OpenSesame()
Dim ClosedBook As Workbook
Dim nameOfWorksheet As String
Dim pathToOpen As String
With Worksheets(1)
nameOfWorksheet = .Range("A10") 'for example
pathToOpen = .Range("ClosedBookFile")
End With
Set ClosedBook = Workbooks.Open(pathToOpen)
ClosedBook.Worksheets(nameOfWorksheet).Activate
Range("A1").Select
End Sub
此外,无论何时引用范围,最好引用工作表。因此,With Worksheets(1)
引用当前工作簿中的第一个工作表。
答案 1 :(得分:0)
沿着@Vityata行,我添加了你需要明确引用带有数据的工作表属于哪个工作簿,并避免隐式引用当前活动的工作簿
这里是压缩代码,上面有
Option Explicit
Sub OpenSesame()
With ThisWorkbook.Worksheets("myWorksheetWithFileInfoName") ' reference worksheet holding info of workbook and worksheet to activate
Workbooks.Open(Filename:=.Range("ClosedBookFile").value).Worksheets(.Range("A2").value).Activate ' open wanted workbook and activate wanted worksheet
'from now on the wanted worksheet in the wanted workbook is the active one
Range("A1").Select ' almost always not needed
End With
End Sub