VBA通过电子表格将新文件名添加到

时间:2018-08-31 08:10:52

标签: excel vba excel-vba

有人可以帮忙吗? (是VBA的新功能)

我正在尝试创建一个VBA,以查看电子表格中当前文件名列表并查找不在列表中的文件名,然后使用新文件名填充电子表格。

例如:

我在“ I”列中有一个文件名列表,我需要VBA将此列表与我的文件位置进行比较,在这种情况下为“ Z:\ CLIENTNAME \ Waiting \ Non-Priority”并添加新文件名。但是VBA不能删除/覆盖已经存在的内容,它只能在下一个可用行上添加新值。如果可以的话,VBA也不应包含文档类型,例如.docx(不是必需的,因为我可以使用公式来消除此问题)。即使工作簿关闭,我也需要VBA才能运行(不确定如何完成)。

下面一直在使用我的代码,但是我面临的问题是:

  • 仅将文件名添加到A列,我似乎无法更改
  • 添加文档类型
  • 下面的代码替换现有值,并且不将当前值与文件夹进行比较
  • 关闭工作簿时不运行

VBA代码:

Sub GetFileNames()
    Dim sPath As String
    Dim sFile As String
    Dim iRow As Integer
    Dim iCol As Integer
    Dim splitFile As Variant

   'specify directory to use - must end in "\"
   sPath = "Z:\NAME\Waiting\Non_Priority\"

   iRow = 1
   sFile = Dir(sPath)
    Do While sFile <> ""
        iRow = iRow + 1
        splitFile = Split(sFile, "-")
        For iCol = 0 To UBound(splitFile)
            Sheet1.Cells(iRow, iCol + 1) = splitFile(iCol)
       Next iCol
       sFile = Dir     ' Get next filename
  Loop
End Sub

谢谢!!

1 个答案:

答案 0 :(得分:0)

如注释中所述,关闭文件后无法运行VBA,但是如果文件已打开并且运行下面的代码,它将获得预期的结果:

Sub GetFileNames()
Dim sPath As String, sFile As String
Dim iRow As Long, iCol As Long
Dim ws As Worksheet: Set ws = Sheet1
'declare and set the worksheet you are working with, amend as required

sPath = "Z:\NAME\Waiting\Non_Priority\"
'specify directory to use - must end in "\"

sFile = Dir(sPath)
Do While sFile <> ""
    LastRow = ws.Cells(ws.Rows.Count, "I").End(xlUp).Row 'get last row on Column I
    Filename = Left(sFile, InStrRev(sFile, ".") - 1) 'remove extension from file
    Set FoundFile = ws.Range("I1:I" & LastRow).Find(What:=Filename, Lookat:=xlWhole) 'search for existing filename
    If FoundFile Is Nothing Then ws.Cells(LastRow + 1, "I") = Filename 'if not found then add it
    sFile = Dir     ' Get next filename
Loop
End Sub