【问题标题】:Code to Skip the File Extension While hyperlink the Files超链接文件时跳过文件扩展名的代码
【发布时间】:2016-12-06 12:18:15
【问题描述】:

结果包括我不想显示的文件扩展名。如何从文本中删除文件扩展名?

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
i = i + 1
Next objFile
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    只需使用LEFT函数将最后四个字符截掉TextToDisplay:=LEFT(objFile.Name, LEN(objFile.Name) - 4)

    【讨论】:

    • 如果扩展名的长度不是 3,它将无法工作。如果扩展名的长度为 2、4 或 3 以外的任何内容,您的代码将失败。在这种特殊情况下,如果扩展名是长度3,它会工作。
    【解决方案2】:

    您可以通过多种方式做到这一点。之前已经回答了这样的问题:https://stackoverflow.com/a/27924854/6151782

    我将尝试以不同的方式处理它,使用拆分。看看下面的代码:

    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
    

    在上面的代码中,我循环直到遇到最后一个点。并且为了避免一个已经尾随的点,我必须放置一个 if 条件,以便它不会附加一个带有空白 finalTextToDisplay 的点(对于第一次迭代,它将是空的)。 您也可以从 1 开始循环,并在循环前设置 finalTextToDisplay 中的值以避免 if 条件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      • 2018-03-19
      • 1970-01-01
      • 2011-11-14
      • 2013-08-03
      • 2017-12-15
      • 1970-01-01
      相关资源
      最近更新 更多