0

我想创建一个宏,它将遍历活动 Excel 工作表中的行。每次循环迭代都会复制 A、B 和 C 列的值。如果第一个单元格是空白的,我想结束循环,除非空单元格在第二行。然后我想继续循环。最终,在复制完所有数据后,我想将复制的数据写入 CSV 文件。这可能吗?

Excel 工作表

我尝试录制一个宏,但解决方案一点也不健壮,因为它不使用循环,而是硬编码Range Selects

Sub Export_to_CSV()
'
' Export_to_CSV Macro
'

'
    Range("A1:C1,A3:C27").Select
    Range("A3").Activate
    Selection.Copy
    Workbooks.Add
    ActiveSheet.Paste
    Sheets("Sheet2").Select
    ActiveWindow.SelectedSheets.Delete
    Sheets("Sheet3").Select
    ActiveWindow.SelectedSheets.Delete
    ChDir "C:\CSV"
    ActiveWorkbook.SaveAs Filename:="C:\CSV\MacroCSV.csv", FileFormat:=xlCSV, _
        CreateBackup:=False
End Sub

谢谢!

4

1 回答 1

2

如果您的要求与您编写的完全一样,那么这应该可以工作。

Option Explicit

Sub Export_To_CSV()

Dim wkbMain as Workbook, wkbCopy as Workbook
Dim wksMain as Worksheet, wksCopy as WOrksheet

Set wkbMain = ThisWorkbook
Set wkbCopy = Workbooks.Add

Set wksMain = wkbMain.Sheets("mySheet")
Set wksCopy = wkbCopy.Sheets(1)

With wksMain
  .Range(.Range("A3"),.Range("C3").End(xlDown)).Copy wksCopy.Range("A1")
End With

With wkbCopy

    Application.DisplayAlerts = False

    Dim x as Integer
    For x = 2 to .Worksheets.Count
        .Sheets(x).Delete
    Next

    Application.DisplayAlerts = True

    .SaveAs Filename:="C:\CSV\MacroCSV.csv", FileFormat:=xlCSV, CreateBackup:=False

End With

End Sub
于 2013-01-10T20:43:03.537 回答