当驱动器从计算机更改为计算机时,将文件版本保存到驱动器

Save version of file to drive, when the drive changes from computer to computer

我制作了一个宏来将我的 xlsm 文件导出到 csv 文件。它在服务器目录为 "I" 的一台计算机上运行良好,但在另一台将同一服务器保存到目录 "T" 的计算机上却失败了。这个 multi-directory/multi-computer 问题有解决方案吗?修剪后的代码附上指出的目录行。

Sub ExportAsCSV()
    Dim Answer As VbMsgBoxResult, Dir As String, LastRow As Long, _
    Date1 As Date, Date2 As Date, CSVFileName As String
' *********************************************************
' Directory String <---------------- The Issue
    Dir = "I:17\CVS" ' Could be "I:\", could be "T:\" ...
' *********************************************************
' Creating the Name of the CSV File using the _
' first and last date in column C (C1 is a header)
    LastRow = Cells(Rows.Count, "C").End(xlUp).Row
    Date1 = Range("C2").Value
    Date2 = Cells(LastRow, "C")
    If Date1 < Date2 Then
        CSVFileName = "FILE." & Format(Date1, "mm.dd.yy") & _
        "-" & Format(Date2, "mm.dd.yy") & ".csv"
    ElseIf Date1 > Date2 Then
        CSVFileName = "FILE." & Format(Date2, "mm.dd.yy") & _
        "-" & Format(Date1, "mm.dd.yy") & ".csv"
    Else
        CSVFileName = "FILE." & Format(Date1, "mm.dd.yy") & ".csv"
    End If

' Double Check User wants to make a sheet Response
    Answer = MsgBox("Clicking 'Yes' will create a CSV file named " & vbCrLf & vbCrLf & _
        "     " & CSVFileName & vbCrLf & vbCrLf & _
        "into " & vbCrLf & vbCrLf & "     " & Dir & vbCrLf & vbCrLf & _
        "It will overwrite any CSV with an identical name." & vbCrLf & vbCrLf & _
        "Is this what you want to do?", vbYesNo + vbQuestion)

'Act based on the Response
    If Answer = vbYes Then
        ' Ready all cells for csv creation
    Dim ws As Worksheet
        Set ws = ActiveWorkbook.Sheets("Sheet1")
        ws.Copy
        ActiveWorkbook.SaveAs FileName:=Dir & "\" & CSVFileName, _
            FileFormat:=xlCSV, CreateBackup:=False
        MsgBox ("Created the csv file:" & vbCrLf & vbCrLf & _
        Dir & "\" & CSVFileName)
    Else
        MsgBox ("Did not create the csv file.")
    End If
End Sub

感谢任何帮助。

您需要使用 UNC 路径而不是映射的网络驱动器。

Dir = "\ServerName\SomeFolder17\CVS"

如果您不知道 server/folder 网络驱动器指向什么,请咨询您的网络管理员。


旁注

您不应该使用全局命名空间中已经存在的 hide/shadow 标识符来命名事物:Dir 实际上是 VBA.FileSystem 模块中的一个函数;通过声明一个 Dir 局部变量,您可以使名称对 reader 有潜在的歧义(尽管编译器不关心)。