简体   繁体   中英

How to specify range in Excel Macro for exporting table to multiple CSV files based on data in column

At work we have two systems, one old and one new, so naturally they do not work well together. The new system exports Excel files, whereas the old system uses CSVs. In a new workbook, I created a Power Query to import the downloaded Excel file and format it closely to what the old system needs. This has the added advantage of just downloading updated files and hitting refresh in the Workbook I created to reformat the data. However, I need to split this data into multiple CSV files based on the data in one column. Normally, I could just filter, copy, and then paste, but there are about 23 departments in this column and over a thousand rows in the Excel file. I did some searching and came across this guide: https://www.howtoexcel.org/vba/how-to-export-your-data-into-separate-workbooks-based-on-the-values-in-a-column/

This is nearly perfect and I like the idea of the button. Though, my table will have only 5 columns. I figured out how to save as.csv and remove the dropdown box to "hard code" the column header that I want. However, I have not figured out how to do the range I need in for the table selection.

ws.Range("Data[#All]").SpecialCells(xlCellTypeVisible).Copy

"Data" is the name of the table that starts on row 4. I need to eliminate the header row from and the fifth column from the export. The number of rows in the table will vary from download to download. How do I subtract off the top row and the last column?

Many thanks, Jon

It's easier to use a ListObject here, accessing the DataBodyRange (which is the body of the table so excludes the header), and then using Resize to grab only the first 4 columns:

Dim table As ListObject
Set table = ws.ListObjects("Data")

table.DataBodyRange.Columns(1).Resize(,4).SpecialCells(xlCellTypeVisible).Copy

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