我的下面的代码应根据数据表A列中的值创建CMR表的副本,然后将值从行复制到CMR副本的特定单元格(单元格索引在数据表中表示为表格的标题)。
代码执行副本,根据值命名它们,并将数据添加到CMR副本的特定单元格。问题是当我有更多的行与一个CMR副本相关时没有。 (例如592):如果CMR拷贝已经存在,则代码应该将数据添加到范围C38:C50的下一个空单元格中。
我至少尝试过if-else语句,但对于现有的表单,它无法正常工作。例如如果名为" 592"已存在它仍在制作名为Sheet(x)的副本。可能ExistingSh总是什么都没有。你能帮忙吗?
另外,我不知道如果我想在C38:C50范围内的第一个空单元格中添加值,而不是直接添加到C38,我怎么能更改else语句。
谢谢,感谢您的所有帮助。
Sub CreateCMR()
Dim ListSh As Worksheet, BaseSh As Worksheet
Dim NewSh As Worksheet
Dim ExistingSh As Worksheet
Dim ListOfNames As Range, LRow As Long, Cell As Range
Dim counter As Integer
With ThisWorkbook
Set ListSh = .Sheets("Data")
Set BaseSh = .Sheets("CMR")
End With
LRow = ListSh.Cells(Rows.Count, "A").End(xlUp).Row
Set ListOfNames = ListSh.Range("A2:A" & LRow)
counter = 2
For Each Cell In ListOfNames
Set ExistingSh = Nothing
On Error Resume Next
Set ExistingSh = Worksheets(Cell.Value)
If ExistingSh Is Nothing Then
BaseSh.Copy After:=Sheets(Sheets.Count)
Set NewSh = ActiveSheet
With NewSh
.Name = Cell.Value
End With
NewSh.Cells(2, 34) = Worksheets("Template2").Cells(counter, 3)
Else
Set ExistingSh = ActiveSheet
ExistingSh.Cells(38, 3) = Worksheets("Template2").Cells(counter, 16)
End If
On Error Goto 0
counter = counter + 1
Next Cell
With Application
.ScreenUpdating = True
End With
ListSh.Activate
MsgBox "Done"
End Sub