【发布时间】:2020-09-06 10:51:41
【问题描述】:
我有一个数据供应工作表,其中是我的两个关键标识列“地址”(唯一值)和“名称”(每个名称都有多个分配的地址)。
每个名称都分配有自己的工作表,该工作表会不断进行编辑,最后将所有信息收集在一个主文件中。
我需要做的: 复制并粘贴地址,如果该地址不在该工作表中,则分配给每个工作表的名称,位于底部。
我尝试过的事情:
- 无法清除工作表内容并粘贴到信息中,因为更新的信息会丢失。
- 将名称与工作表名称匹配并粘贴到完整的行上,但这只是添加到底部。粘贴不仅匹配新行的所有值。
- 查询以添加新地址 - 刷新查询时会出现问题,因为所有信息都被覆盖并且更新的信息现在不再与地址匹配。
Sub new_cases()
Dim cell As Range
Dim cmt As Comment
Dim bolFound As Boolean
Dim sheetnames() As String
Dim lngitem As Long, lnglastrow As Long
Dim sht As Worksheet, shtmaster As Worksheet
Dim MatchRow As Variant
Set shtmaster = ThisWorkbook.Worksheets("data_supply")
'collect names for all other sheets
ReDim sheetnames(0)
For Each sht In ThisWorkbook.Worksheets
If sht.Name <> shtmaster.Name Then
sheetnames(UBound(sheetnames)) = sht.Name
ReDim Preserve sheetnames(UBound(sheetnames) + 1)
End If
Next sht
ReDim Preserve sheetnames(UBound(sheetnames) - 1)
For Each cell In shtmaster.Range("P2:P" & shtmaster.Cells(shtmaster.Rows.Count, "P").End(xlUp).Row)
bolFound = False
If Not IsError(Application.Match(cell.Value2, sheetnames, 0)) Then
bolFound = True
Set sht = ThisWorkbook.Worksheets(sheetnames(Application.Match(cell.Value2, sheetnames, 0)))
' Tried finding a way to do unique match for column E
MatchRow = Application.Match(?????????)
If Not IsError(MatchRow) Then
shtmaster.Rows(cell.Row).EntireRow.Copy Destination:=sht.Cells(MatchRow, 1)
Else 'no match in sheet, add the record at the end
On Error GoTo SetFirst
lnglastrow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1
On Error GoTo 0
shtmaster.Rows(cell.Row).EntireRow.Copy Destination:=sht.Cells(lnglastrow, 1)
End If
End If
If bolFound = False Then
For Each cmt In shtmaster.Comments
If cmt.Parent.Address = cell.Address Then cmt.Delete
Next cmt
cell.AddComment "no sheet found for this row"
ActiveSheet.EnableCalculation = False
ActiveSheet.EnableCalculation = True
End If
Set sht = Nothing
Next
Exit Sub
SetFirst:
lnglastrow = 1
Resume Next
End Sub
【问题讨论】:
-
您能否确认是否要从主表中写入数据。你的第二个解决方案有什么问题?尝试澄清一下,尤其是但这只是添加到底部。
-
您好 VBasic2008。是的,我正在尝试从主表 data_supply 中写入。第二种解决方案很好,但它粘贴了所有匹配的值,而不仅仅是粘贴新行(工作表中还没有的行)。如果存在唯一 ID,我可以执行该选项,然后运行删除重复行似乎有点混乱