Question: How can I write an Excel macro that needs to compare data in Cell A2 to A3 and so on until it doesn't find a match? So if there were 100 rows in the sheet and the data in column A for the first 50 were equal, but A51 contained a different value and you wanted to copy the data from A2 through A50 into a new workbook. The workbook would then be saved with the same name as the value found in cell A2. Then the macro would continue comparing the values in column A starting from Cell A51 until a different value was encountered. It would then copy the data into another new workbook and so on...until all values had been evaluated in column A. Answer: You should be able to create a macro that tests each value in column A and checks for differences. Let's take a look at an example. Download Excel spreadsheet (as demonstrated below)
|
In our spreadsheet, we've created a button on the Data sheet called "Copy Data". When the user clicks on this button, a macro called CopyData will run. This macro will analyze each value in column A to search for a different value. When a different value is found in column A on the Data sheet, the macro will then copy the values in columns A through D up to the different value, and paste into a new workbook. So in this example, it copies all rows until it reaches the Microsoft value in cell A8 (on the Data sheet) and pastes these values to a new workbook. The macro then saves the new workbook with the name found in column A. So the first workbook would be saved as "Tech on the Net.xls". The LPath variable determines where this file will be saved. The macro then goes back to column A on the Data sheet and continues analyzing the value starting from cell A8. It then creates another workbook called "Microsoft.xls" and copies the Microsoft data into this new workbook.
|
When the macro has completed, the above message box will appear. It identifies the number of new workbooks that were created and where to find them. In this example, we've created two workbooks: C:\Tech on the Net.xls See pictures below:
|
You will need to customize the LPath variable so that the new workbook files are saved to the directory that you want. You can press Alt-F11 to view the VBA code. Macro Code:The macro code looks like this:
|
Visit our busy book shop, were you can find latest books for beginners as well as advanced excel users.
Spreadsheet 123 Spreadsheet Software Development
See Spreadsheets for:
a.Hotel Management b.Personal Budget
c.Corporate Finance d.Rating Calculation e.Real Estate and Mortgage
f.Web Calc