如何在VBA中定义文件目录

时间:2015-02-16 23:13:56

标签: excel vba excel-vba

我现在正在自己学习VBA excel。正如我们在excel中所知,我们可以将一个文件目录放在一个函数中,以将文件中的一个值链接到另一个文件。比如说在单元格中我们可以这样做

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

如何将其添加到VBA脚本中? 最终我怎样才能预先定义“目录”,“文件名”,“工作表名称”甚至单元格位置等等

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

2 个答案:

答案 0 :(得分:2)

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

请注意,文件路径的代码测试是有效的

您的后续问题

[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

答案 1 :(得分:0)

我“想”你问的是如何将该字符串拆分为组件是吗?这是一个很长的啰嗦,但很好地了解如何使用字符串,我希望它可以帮助您学习。我已经为你评论了每一行。

一开始看起来有点令人生畏,但如果你对split命令和数组感到满意,那么它将帮助你向前移动:

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中,看看你是否可以关注它。

有许多方法可以使用字符串,我倾向于使用分割和数组操作,但很多人会使用Mid,Left,Right和Find / Instr的组合。