我“认为”您是在问如何将该字符串拆分为组件,是吗?这是相当长篇大论的,但对如何弹奏弦乐有很好的了解,我希望它对你的学习有所帮助。我已经为你注释了每一行。
一开始这似乎有点令人生畏,但如果您现在对 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 的组合。