将select导出到CSV

我已经为我们的客户创build了一个excel电子表格模板来填充并发回给我们。 我想手动select他们填充的数据并保存为一个.csv导入到另一个软件。 我首先通过录制一个macros来尝试这个。 这不起作用,因为不同的客户发送不同数量的logging。

我已经尝试过来自在线研究的代码片段,并提出了这个问题。

Sub Select_To_CSV() Dim rng As Range Dim myrangearea() Range(ActiveCell, ActiveCell.End(xlDown).End(xlToRight)).Select Dim myPath As String, v myPath = "p:\" & _ Format(Date, "yyyymmdd") & ".csv" 'myPath = "x:\" & Format(Date, "yyyymmdd") & ".csv" v = SaveAs(myPath) If v <> False Then ThisWorkbook.SaveAs v End Sub Function SaveAs(initialFilename As String) On Error GoTo EndNow SaveAs = False With Application.FileDialog(msoFileDialogSaveAs) .AllowMultiSelect = False .ButtonName = "&Save As" .initialFilename = initialFilename .Title = "File Save As" '.Execute .Show SaveAs = .SelectedItems(1) End With EndNow: End Function Sub Select_To_CSV() Dim rng As Range Dim myrangearea() Range(ActiveCell, ActiveCell.End(xlDown).End(xlToRight)).Select Dim myPath As String, v myPath = "p:\" & _ Format(Date, "yyyymmdd") & ".csv" 'myPath = "x:\" & Format(Date, "yyyymmdd") & ".csv" v = SaveAs(myPath) If v <> False Then ThisWorkbook.SaveAs v End Sub 

这工作得很好,除了当我回去看看文件夹中的.csv,它是相同的工作表,而不是选定的列。

最终,我期待的是,

  1. 手动select我想要的列
  2. 运行一个将所选列转换为.csv的macros
  3. 出现另存为对话框
  4. 导航到我想要的某个文件夹。

干得好:

 Sub MacroMan() ChDrive "P:" '// <~~ change current drive to P:\ Dim copyRng As Excel.Range Dim ThisWB As Excel.Workbook Dim OtherWB As Excel.Workbook Dim sName As String '// set reference to the 'Master' workbook Set ThisWB = ActiveWorkbook '// assign selected range to 'copyRng' Set copyRng = Application.InputBox(Prompt:="Select range to convert to CSV", Type:=8) '// If the user selected a range, then proceed with rest of code: If Not copyRng Is Nothing Then '// Create a new workbook with 1 sheet. Set OtherWB = Workbooks.Add(1) '// Get A1, then expand this 'selection' to the same size as copyRng. '// Then assign the value of copyRng to this area (similar to copy/paste) OtherWB.Sheets(1).Range("A1").Resize(copyRng.Rows.Count, copyRng.Columns.Count).Value = copyRng.Value '// Get save name for CSV file. sName = Application.GetSaveAsFilename(FileFilter:="CSV files (*.csv), *.csv") '// If the user entered a save name then proceed: If Not LCase(sName) = "false" Then '// Turn off alerts Application.DisplayAlerts = False '// Save the 'copy' workbook as a CSV file OtherWB.SaveAs sName, xlCSV '// Close the 'copy' workbook OtherWB.Close '// Turn alerts back on Application.DisplayAlerts = True End If '// Make the 'Master' workbook the active workbook again ThisWB.Activate MsgBox "Conversion complete", vbInformation End If End Sub 

这将允许您手动select范围(包括整列)。 然后,它会将所述范围转移到新工作表上,使用“另存为”对话框将该工作表另存为CSV,然后closures该工作表。