如何在VBA中定义文件目录

我现在正在学习Excel中的VBA。 正如我们在Excel中所知道的那样,我们可以在一个函数中放置一个文件目录,将文件中的一个值链接到另一个文件。 举个例子,在一个单元格里,我们可以做到这一点

B2 ='C:\directory\[filename.xlsx]sheetname'!A1 

我怎样才能把这个到VBA脚本? 最终如何预先定义“目录”,“文件名”,“工作表名称”,甚至是单元格的位置

 directory = "myfolder\myfolder2\.." cell = "A1" 

鉴于你正在学习,你会做这样的事情

请注意,代码testing的文件path是有效的

你的后续问题

 [b2] = "='" & strPath & "[" & strFile & "]" & strSht & "'!" & strCell [b2].Copy [b3:b4] 

原版的

 Sub Test() Dim strPath As String Dim strFile As String Dim strSht As String Dim strCell As String strSht = "Sheet2" strCell = "A1" strPath = "C:\temp\" strFile = "test.xlsx" If Len(Dir(strPath & strFile)) > 0 Then [b2] = "='" & strPath & "[" & strFile & "]" & strSht & "'!" & strCell Else MsgBox "invalid file", vbCritical End If End Sub 

我“想”你问如何将这个string拆分成组件是吗? 这是很长的啰嗦,但很好的洞察如何玩string,我希望它可以帮助你学习。 我已经为你评论每一行。

起初看起来有点令人生畏,但是如果现在对分割命令和数组感到满意,它将会帮助你向前迈进:

 Sub SplitCellContents() Dim MyString As String, MySheetName As String, MyCell As String, MyDrive As String, MyDir As String, MyFileName As String MyString = "'C:\directory\[filename.xlsx]sheetname'!A1" 'Set the string value MyCell = Split(MyString, "!")(UBound(Split(MyString, "!"))) 'Split the string into an array on the ! and take the last value in the array MySheetName = Split(Split(MyString, "]")(UBound(Split(MyString, "]"))), "'")(0) 'Split the string into an array on "]" then split the resulting last value and split again on "'" and take the first value ' Look at what the above line does, split on ] gives a last value of sheetname'!A1 then split that on ' gives us a first value of sheetname MyDrive = Replace(Split(MyString, "\")(0), "'", "") 'Split the string on \ and take first value MyString = Replace(MyString, "'" & MyDrive, "") 'Chop out the drive reference from the string to allow further manipulation MyString = Replace(MyString, "'!" & MyCell, "") 'Chop out the cell reference from the string to allow further manupulation MyFileName = Replace(Replace(Split(MyString, "[")(UBound(Split(MyString, "["))), "]", ""), MySheetName, "") 'Similar to what we do for mycell, see if you can work out how MyDir = Replace(Replace(MyString, "[" & MyFileName & "]", ""), MySheetName, "") ' Replace the fileName and sheetname in the string with nothing, should leave the DIR MsgBox "MyCell = " & MyCell & vbLf & _ "MySheetName = " & MySheetName & vbLf & _ "MyDrive = " & MyDrive & vbLf & _ "MyDir = " & MyDir & vbLf & _ "MyFileName = " & MyFileName 'Output to a messagebox End Sub 

看起来很可怕,但粘贴到VBE,看看你是否可以按照它。

有很多方法来玩弄string,我倾向于更喜欢分割和数组操作,但是很多人会使用Mid,Left,Right和Find / Instr的组合。