修改VBA导出CSV代码:从指定单元格取文件名并保存至预设路径
Hey there! I've adjusted your VBA code to pull the save filename from cell N15 and save the CSV to a preset path. Here's the updated version, plus breakdowns of the key tweaks:
Modified VBA Code
Sub ExportAsCSV() Dim MyFileName As String Dim PresetPath As String Dim CurrentWB As Workbook, TempWB As Workbook Dim FileNameFromCell As String Set CurrentWB = ActiveWorkbook ' Get the filename from cell N15 of the active sheet FileNameFromCell = Trim(CurrentWB.ActiveSheet.Range("N15").Value) ' Check if the cell is empty (adds robustness) If FileNameFromCell = "" Then MsgBox "Please enter a filename in cell N15!", vbExclamation Exit Sub End If ' Set your preset path here (make sure it ends with a backslash) PresetPath = "C:\Your\Preset\Save\Path\" ' Replace with your actual folder path ' Copy used range to temporary workbook CurrentWB.ActiveSheet.UsedRange.Copy Set TempWB = Application.Workbooks.Add(1) With TempWB.Sheets(1).Range("A1") .PasteSpecial xlPasteValues .PasteSpecial xlPasteFormats End With ' Build the full file path: preset path + filename + .csv extension MyFileName = PresetPath & FileNameFromCell & ".csv" Application.DisplayAlerts = False TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True TempWB.Close SaveChanges:=False Application.DisplayAlerts = True MsgBox "CSV saved successfully to: " & MyFileName, vbInformation End Sub
Key Changes Explained
- Filename from cell N15: We added
FileNameFromCell = Trim(CurrentWB.ActiveSheet.Range("N15").Value)to grab the text from your target cell, plus a quick check to ensure the cell isn't empty (prevents blank filenames). - Preset path setup: The
PresetPathvariable lets you define your fixed save location. Just replace the example path with your actual folder — don't forget to keep the trailing backslash (\) to avoid path errors. - Updated file path logic: Instead of relying on the current workbook's name, we now combine the preset path with the N15 filename and append the
.csvextension automatically. - Success confirmation: Added a popup to show the final save path, so you can instantly verify the file landed where you expected.
Quick Extra Tips
- If you want the code to create the preset folder automatically if it doesn't exist, add this right before building
MyFileName:If Dir(PresetPath, vbDirectory) = "" Then MkDir PresetPath End If - If you'd prefer to store the preset path in a cell instead of hardcoding it, swap the
PresetPathassignment with something likePresetPath = Trim(CurrentWB.ActiveSheet.Range("Z1").Value)(adjust the cell reference to match your setup).
内容的提问来源于stack exchange,提问作者Brijesh
相关产品推荐
相关产品推荐

