文件重命名代码返回单个文件名为' 0'?为什么呢?

时间:2017-12-27 18:22:47

标签: excel vba excel-vba

我有一张带有两列的excel表。在A列中,我从特定文件夹中获取文件名。在B列中,我使用Vlook-up和几个连接从不同的表中获取新文件名。

使用B列中的以下代码,我能够重命名所选文件夹中的文件名。代码工作正常,除了将单个文件重命名为' 0',它不应该这样做。仅供参考,这是excel表格列中的第一个文件" A"它应该重命名的是重新命名为' 0'。

Sub RenameFiles()
    Dim xDir As String
    Dim xFile As String
    Dim xRow As Long
    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
    If .Show = -1 Then
        xDir = .SelectedItems(1)
        xFile = Dir(xDir & Application.PathSeparator & "*")
        Do Until xFile = ""
            xRow = 0
            On Error Resume Next
            xRow = Application.Match(xFile, Range("A:A"), 0)
            If xRow > 0 Then
                Name xDir & Application.PathSeparator & xFile As _
                xDir & Application.PathSeparator & Cells(xRow, "B").Value
            End If
            xFile = Dir
        Loop
    End If
    End With

    Dim conState As ADODB.Connection
    Dim strSQL As String
    Dim ObjWshNw As Object
    Dim strUsername As String
    Dim strComputerName As String

    Set conState = New Connection
    Set ObjWshNw = CreateObject("WScript.Network")
    strUsername = ObjWshNw.UserDomain & "\" & ObjWshNw.UserName
    strComputerName = ObjWshNw.ComputerName

    dtEnd = Now()

    With conState
        .Provider = "SQLOLEDB.1"
        .ConnectionString = "server=xxxxxxx; Trusted_Connection=Yes"
        .Open
    End With

    'Inject the strSQL into the ADODB Connection and run it
    strSQL = _
            "insert into ggghhh.yyyyy.yyyy(ReportName,ReportStart,ReportEnd,Username,ComputerName,RuntimeSeconds) " & _
            "values ('" & strReportName & "','" & dtStart & "','" & dtEnd & "','" & strUsername & "','" & strComputerName & "'," & DateDiff("s", CDate(dtStart), CDate(dtEnd)) & ")"
    conState.Execute strSQL


    End Sub

请告诉我代码中需要修改的内容,以确保单个文件名未被重命名为' 0'。

0 个答案:

没有答案