File Name Extract From String 每隔一段时间工作一次

File Name Extract From String works every other time

我需要帮助来理解为什么从字符串中提取文件名只能每隔一段时间进行一次。

右边和中间我都试过了。我以前在其他代码中使用过没有问题。我正在使用 msgbox 进行调试。

最终结果应该是在 table

的底部添加多个文件名
Private Sub ButtonAdd_Click()
    Dim fd As FileDialog
    Dim fName As String ' full path file name
    Dim nextRow As Long
    Dim filename As String ' extracted file name only

    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.Title = "Please select file to add"
    fd.InitialFileName = ThisWorkbook.FullName
    fd.AllowMultiSelect = True
    fchosen = fd.Show

    If fchosen = -1 Then
        For i = 1 To fd.SelectedItems.Count
            fName = fd.SelectedItems(i)
            
            'filename = Right(fName, Len(fName) - InStrRev(filename, "\"))
            filename = Mid(fName, InStrRev(filename, "\") + 1)
            
            MsgBox (filename)
            nextRow = Range("a" & Rows.Count).End(xlUp).row + 1
            'Range("a" & nextRow) = filename
        Next i
    End If
End Sub

任你选

从文件路径获取文件名

Option Explicit

Sub Sample()
    MsgBox GetFilenameFromPath("C:\Temp\Myfile.Txt")
End Sub

Private Function GetFilenameFromPath(ByVal strPath As String) As String
    If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
        GetFilenameFromPath = GetFilenameFromPath( _
        Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
    End If
End Function

获取不带扩展名的文件名

Option Explicit

Sub Sample()
    Dim fName As String
    fName = "C:\Temp\Myfile.Txt"
    
    MsgBox GetFilenameFromPath(Left(fName, (InStrRev(fName, ".", -1, vbTextCompare) - 1)))
End Sub

Private Function GetFilenameFromPath(ByVal strPath As String) As String
    If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
        GetFilenameFromPath = GetFilenameFromPath( _
        Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
    End If
End Function

正如 Josh 在评论中所写,您使用了错误的变量 filename 而不是 fname。嵌套命令如何使查找错误变得困难以及变量命名如何重要的另一个示例。

将行分成两部分并将 fname 重命名为 fullFilename:

Dim fullFilename as string, filename as string, p as long
fullFilename = fd.SelectedItems(i)
p = InStrRev(fullFilename, "\")
if p > 0 then
    filename = mid(fullFilename, p+1)
else
    filename = fullFilename
End If

现在您可以轻松区分包含完整路径的变量和仅包含文件名的变量。即使你混淆了一些东西,你也可以使用调试器轻松找到问题