跳过文件扩展名的代码,同时为文件创建超链接。
跳过文件扩展名的代码,同时为文件创建超链接。
结果包括我不想显示的文件扩展名。如何从文本中删除文件扩展名?
Sub mymacro() Dim objcreate As Object, objFolder As Object, objFile As Object, i As Integer Dim ws As Worksheet, rng As Range Set ws = Sheets("Sheet1") Set rng = ws.Range("C1") Set objcreate = createobject("Scripting.FileSystemObject") Set objFolder = objcreate.GetFolder(rng) i = 0 For Each objFile In objFolder.Files 'select cell Range(Cells(i + 1, 1), Cells(i + 1, 1)).Select 'create hyperlink in selected cell ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _ objFile.Path, _ TextToDisplay:=Left(objFile.Name, InStrRev(objFile.Name, ".") - 1) i = i + 1 Next objFile End Sub
问题的出现原因:
在给文件创建超链接时,希望在显示的文本中去除文件扩展名。现有的代码中使用了split函数来处理文件名,但在处理过程中出现了一些问题。
解决方法:
为了去除文件扩展名,代码中使用了split函数来分割文件名,并通过循环取得最后一个点之前的子字符串。为了避免在最后一个循环中多余地添加一个点,需要使用if条件来判断最后一个子字符串是否为空,并避免与finalTextToDisplay拼接。也可以在循环之前将finalTextToDisplay初始化为一个非空的字符串,从而避免使用if条件。
下面是修正后的代码:
Sub mymacro() Dim objcreate As Object, objFolder As Object, objFile As Object, i As Integer Dim ws As Worksheet, rng As Range Set ws = Sheets("Sheet1") Set rng = ws.Range("C1") Set objcreate = createobject("Scripting.FileSystemObject") Set objFolder = objcreate.GetFolder(rng) i = 0 For Each objFile In objFolder.Files 'select cell Range(Cells(i + 1, 1), Cells(i + 1, 1)).Select 'create hyperlink in selected cell ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:= _ objFile.Path, _ TextToDisplay:=objFile.Name tmpArr = Split(TextToDisplay,".") Dim finalTextToDisplay tmpArr = split(TextToDisplay,".") finalTextToDisplay = "" 'considering there might be a dot in the file name itself, we will take the string till the last dot using loop loopLimit = UBound(tmpArr) for j=0 to loopLimit-1 if i = 0 then finalTextToDisplay = tmpArr(j) else finalTextToDisplay =tmpArr(j) & "." & finalTextToDisplay end if Next i = i + 1 Next objFile End Sub
以上代码通过循环遍历文件名中的各个子字符串,并将它们拼接起来,最后得到一个去除扩展名的文件名。