如何将不同的固定行拆分成不同的格式?

时间:2017-09-03 17:28:26

标签: vba excel-vba excel-formula excel

示例数据:goo.gl/akWozD(假设有1百万行,8列)

如何编辑下面的VBA代码以生成具有不同固定行的不同文件格式(CSV和Excel)?例如:InputBox同时要求CSV固定行大小和Excel固定行大小。

所需的输出为CSV 1, CSV 2, CSV 3, etcExcel 1, Excel 2, Excel 3, etc,其中CSV具有X个固定行,Excel具有Y个固定行,位于同一文件夹中。原始工作簿将不会更改/修改。运行宏时将询问XY

谢谢。

Public Sub SplitFixedRows()
  Dim wbOrig As Workbook
  Dim wb As Workbook
  Dim ThisSheet As Worksheet
  Dim NumOfColumns As Integer
  Dim RangeToCopy As Range
  Dim RangeOfHeader As Range
  Dim WorkbookCounter As Integer
  Dim RowsInFile

  Application.ScreenUpdating = False
  RowsInFile = InputBox("Please enter data size +1 header (Example: 11, 101, 501): ")

  Set wbOrig = ActiveWorkbook
  Set ThisSheet = wbOrig.ActiveSheet
  NumOfColumns = ThisSheet.UsedRange.Columns.Count
  WorkbookCounter = 1

  Set RangeOfHeader = ThisSheet.Range(ThisSheet.Cells(1, 1), ThisSheet.Cells(1, NumOfColumns))
  For p = 2 To ThisSheet.UsedRange.Rows.Count Step RowsInFile - 1
    Set wb = Workbooks.Add

    RangeOfHeader.Copy wb.Sheets(1).Range("A1")

    Set RangeToCopy = ThisSheet.Range(ThisSheet.Cells(p, 1), ThisSheet.Cells(p + RowsInFile - 2, NumOfColumns))
    RangeToCopy.Copy wb.Sheets(1).Range("A2")

    wb.SaveAs wbOrig.Path & "\Data " & WorkbookCounter
    wb.Close

    WorkbookCounter = WorkbookCounter + 1
  Next p

  Application.ScreenUpdating = True
  Set wb = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你只会缺少CSV个文件。这可以通过以下步骤完成:

Dim FSO, wfile As Object
Dim content As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Set wfile = FSO.OpenTextFile("path to the file", 2) 'connection for writing

'here you prepare whole content of the file

wfile.Write content
wfile.Close

为了准备文件的content,您只需在逗号(或任何您想要的)之间的连续单元格中附加值。要做到这一点,你只需要遍历范围:)