excel最后一列是供应商字段,请用vba语句将不同供应商生成不同的sheet表
时间: 2023-08-18 15:04:22 浏览: 175
excel vba生成建表语句
Sure! Here's an updated VBA code that generates different sheets based on the values in the last column (column with the header "Supplier"):
```vba
Sub GenerateSheets()
Dim ws As Worksheet
Dim newWs As Worksheet
Dim lastRow As Long
Dim cellValue As Variant
Dim supplierCol As Range
' Set the worksheet and range for the supplier column
Set ws = ThisWorkbook.ActiveSheet
lastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
Set supplierCol = ws.Range("A1:A" & lastRow)
' Create a dictionary to store unique supplier names
Dim supplierDict As Object
Set supplierDict = CreateObject("Scripting.Dictionary")
' Loop through the supplier column and add unique names to the dictionary
For Each cell In supplierCol
cellValue = cell.Value
If Not supplierDict.exists(cellValue) Then
supplierDict.Add cellValue, True
End If
Next cell
' Create a new sheet for each unique supplier name
For Each key In supplierDict.keys
Set newWs = ThisWorkbook.Worksheets.Add
newWs.Name = key
' Filter the data based on the current supplier and copy to the new sheet
ws.AutoFilterMode = False
supplierCol.AutoFilter Field:=1, Criteria1:=key
ws.UsedRange.SpecialCells(xlCellTypeVisible).Copy newWs.Range("A1")
ws.AutoFilterMode = False
' Adjust the column widths in the new sheet if necessary
newWs.Columns.AutoFit
Next key
' Show a message box when finished
MsgBox "Sheets generated based on suppliers!"
End Sub
```
You can copy this code into a VBA module in the Excel VBA editor (press `Alt+F11` to open the VBA editor). Make sure you have saved your workbook before running this macro, as it will make changes to the workbook. Run the macro, and it will create separate sheets for each unique supplier in the last column of the active sheet. The data related to each supplier will be filtered and copied to the respective sheet.
Note: This code assumes that the last column in your worksheet is the "Supplier" column, and it uses the active sheet as the source. Please adjust the code accordingly if your requirements are different.
阅读全文