我目前正在为Excel应用程序首次使用VB脚本。我需要获取我正在处理的文件的路径和名称,并将其传递给变量,以便我可以使用它将一些数据从另一个文件中的同一文件复制回同一文件中。< / p>
答案 0 :(得分:0)
像
这样的东西Dim completeName as String
completeName = ThisWorkbook.fullname
Dim file_Name as String
file_Name= ThisWorkbook.name
Dim file_path as String
file_path = ThisWorkbook.path
答案 1 :(得分:0)
以下是获取工作簿的文件路径和文件名的方法:
Option Explicit
Private Sub Path()
Dim sFilePath As String
Dim sFileName As String
'This returns the path of the workbook
'without a final \ and without the name
'i.e. C:\Test
sFilePath = ThisWorkbook.Path
MsgBox sFilePath
'This returns the fill path of the workbook
'including the file name, such as
'C:\Test\Book1.xlsm
sFilePath = ThisWorkbook.FullName
MsgBox sFilePath
'This returns the name of the workbook
sFileName = ThisWorkbook.Name
MsgBox sFileName
End Sub
打开VB编辑器(通过按 ALT + F11 或在“开发工具”选项卡下 - > Visual Basic)。
右键单击Microsoft Excel Objects - &gt;插入 - &gt;模块化并粘贴代码并运行它以查看结果。
使用&#34; data&#34;一词打开工作簿sFileName
附加后,您可以使用&
来连接字符串和变量,如下所示:
Option Explicit
Private Sub Path()
Dim sFileName As String
'This returns the name of the workbook without .xls extension
sFileName = Left(ThisWorkbook.Name, (InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1))
MsgBox "R:Downloads\" & sFileName & "data.xlsx"
Workbooks.Open Filename:="R:Downloads\" & sFileName & "data.xlsx"
End Sub
设置sFileName
的行只是采用book1.xlsx
并返回book1
。我这样做是为了处理任何文件扩展名(即不是查找和替换&#34; .xlsx&#34;)。