简体   繁体   English

根据单元格值与工作表名称将行分配到各个工作表

[英]Distribute rows to individual sheets based on cell value vs sheet name

I have this vba code that appends/distributes records from a Data mastersheet to individual named sheets.我有这个 vba 代码,它将数据主表中的记录附加/分发到单个命名表。 This is done based on column E's value.这是根据 E 列的值完成的。 It works fine but ends in an error whenever it encounters a value on column E that's not one of the sheets in the file.它工作正常,但只要在 E 列上遇到不是文件中的工作表之一的值时,就会以错误结束。 Can you please help me so as to allow it to just skip those records and proceed with the processing?你能帮我让它跳过那些记录并继续处理吗? Thanks!谢谢!

Sub CopyDataToSheets()


Dim copyfromws As Worksheet
Dim copytows As Worksheet
Dim cfrng As Range
Dim ctrng As Range
Dim cflr As Long
Dim ctlr As Long
Dim i As Long
Dim currval As String


Set copyfromws = Sheets("Data")
cflr = copyfromws.Cells(Rows.Count, "B").End(xlUp).Row

'   Copy Row of Data to Specific Worksheet based on value in Column E
'   Existing Formulas in Columns F through H or J are automatically extended to the new row of data
For i = 2 To cflr
    currval = copyfromws.Cells(i, 1).Value
    Set copytows = Sheets(currval)
    ctlr = copytows.Cells(Rows.Count, "B").End(xlUp).Row + 1
    Set cfrng = copyfromws.Range("A" & i & ":N" & i)
    Set ctrng = copytows.Range("A" & ctlr & ":N" & ctlr)
    ctrng.Value = cfrng.Value
Next


End Sub

I would make a small helper function that can test if the worksheet exists.我会做一个小帮手 function 可以测试工作表是否存在。 That way you can control the logic of your loop.这样您就可以控制循环的逻辑。

Function SheetExists(sheetName As String, Optional wb As Workbook) As Boolean
    If wb Is Nothing Then Set wb = ThisWorkbook
    Dim ws As Worksheet
    
    On Error Resume Next
    Set ws = wb.Sheets(sheetName)
    SheetExists = Err = 0
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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