修改宏以消除对话框并打开新创建的文件

Modify macro to eliminate dialog box and open newly created file

提问人:Sonny 提问时间:9/14/2023 更新时间:9/14/2023 访问量:30

问:

希望你一切安好。我还是个新手,所以请耐心等待我。

我正在尝试将 excel 中的范围保存到单独的 CSV 文件中。 我发现这段代码有效,但我想进行 2 次修改。我对打开的对话框不感兴趣,要求我保存文件。如果它只是保存在当前文件夹中,那对我来说很好。另外,有没有办法在创建新创建的 CSV 文件后自动打开它?

谢谢

桑尼


    Option Explicit
 
Public Sub ExcelRowsToCSV()
 
  Dim iPtr As Integer
  Dim sFileName As String
  Dim intFH As Integer
  Dim aRange As Range
  Dim iLastColumn As Integer
  Dim oCell As Range
  Dim iRec As Long
 
  Set aRange = Range("D1:V39")
  iLastColumn = aRange.Column + aRange.Columns.Count - 1
  
  iPtr = InStrRev(ActiveWorkbook.FullName, ".")
  sFileName = Left(ActiveWorkbook.FullName, iPtr - 1) & Format(Date, " mmm dd, yyyy ") & ".csv"
  sFileName = Application.GetSaveAsFilename(InitialFileName:=sFileName, FileFilter:="CSV (Comma delimited) (*.csv), *.csv")
  If sFileName = "False" Then Exit Sub
    
  Close
  intFH = FreeFile()
  Open sFileName For Output As intFH
  
  iRec = 0
  For Each oCell In aRange
    If oCell.Column = iLastColumn Then
      Print #intFH, oCell.Value
      iRec = iRec + 1
    Else
      Print #intFH, oCell.Value; ",";
    End If
  Next oCell
   
  Close intFH
  
  MsgBox "Finished: " & CStr(iRec) & " records written to " _
     & sFileName & Space(10), vbOKOnly + vbInformation
 
End Sub
Excel VBA CSV

评论


答:

0赞 Tim Williams 9/14/2023 #1
sFileName = ActiveWorkbook.Path & "\" & Left(ActiveWorkbook.FullName, iPtr - 1) & _
            Format(Date, " mmm dd, yyyy ") & ".csv"

将保存到与 ActiveWorkbook 相同的文件夹中(前提是工作簿已保存在某处)

Workbooks.Open(sFileName)将在 Excel 中打开保存的文件。

0赞 taller 9/14/2023 #2

创建一个新工作簿,复制数据并另存为 CSV 而不是 CSV。避免重新打开 csv 文件。open/print

Option Explicit
Public Sub ExcelRowsToCSV()
    Dim iPtr As Integer
    Dim sFileName As String
    Dim aRange As Range
    Dim newWK As Workbook
    Set aRange = ActiveWorkbook.ActiveSheet.Range("D1:V39")
    iPtr = InStrRev(ActiveWorkbook.FullName, ".")
    sFileName = Left(ActiveWorkbook.FullName, iPtr - 1) & Format(Date, " mmm dd, yyyy ") & ".csv"
    Set newWK = Workbooks.Add
    With aRange
        newWK.ActiveSheet.Range("A1").Resize(.Rows.Count, .Columns.Count).Value = .Value
    End With
    newWK.SaveAs Filename:=sFileName, _
        FileFormat:=xlCSVUTF8, CreateBackup:=False
    MsgBox "Finished: " & CStr(aRange.Rows.Count) & " records written to " _
        & sFileName & Space(10), vbOKOnly + vbInformation
End Sub

评论

0赞 Sonny 9/16/2023
谢谢。是否可以默认保存到 c 驱动器上的特定位置?刚刚发现,我们的程序无法从共享驱动器加载。谢谢
0赞 Sonny 9/16/2023
尝试添加ChDir“C:\temp”,但似乎不起作用。
1赞 taller 9/16/2023
sDir = "C:\temp" iPtr = InStrRev(ActiveWorkbook.Name, ".") sfilename = sDir & "\" & Left(ActiveWorkbook.Name, iPtr - 1) & Format(Date, " mmm dd, yyyy ") & ".csv"
0赞 Sonny 9/16/2023
嗨,taller_ExcelHome,我添加了 Dim sDir As String 并让它工作。谢谢。