简体   繁体   中英

Issue with export header and each two rows by macro from Excel to csv

I want to export data from master Excel to CSV files.

在此处输入图像描述

As you can see, first row is header, and every two rows will be copied into new CSV file. The CSV file is named by City (from row without diacritics) and by predefined words. Here is my macro:

    Sub Macro1()

Dim newWB As Workbook
Dim myWS As Worksheet
Dim lastRow As Long

Set myWS = ThisWorkbook.Worksheets("ExportSamospravy")

With myWS

    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

    For x = 2 To lastRow
    
        Set newWB = Workbooks.Add

        newWB.Sheets("Hárok1").Rows(1) = myWS.Rows(1).Value
        newWB.Sheets("Hárok1").Rows(2) = myWS.Rows(x).Value
        newWB.Sheets("Hárok1").Rows(3) = myWS.Rows(x).Value

        
        newWB.SaveAs Filename:="C:\Users\andre\OneDrive\prispevky\smart-cities\data\1-2021\Export\EconomySamospravy\" & Range("I2").Value & "EconomySamospravy", FileFormat:=xlCSV

        Columns(9).EntireColumn.Delete
        Columns(9).EntireColumn.Delete

        newWB.Close True
        
    Next x
    
End With

End Sub

My issue is that only row 2019 is multiplied into second row. Also it has issue with saving.

I found solution

    For x = 2 To lastRow Step 2
n = x + 1
    Set newWB = Workbooks.Add

Now it exports perfectly!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM