根据匹配结果将值从wkbk 1返回到wkbk 2

问题描述

我在下面评论了我的代码。我正在尝试遍历当前工作簿以搜索具有蓝色边框的单元格(我目前仅使用Col A进行测试)。

如果单元格具有蓝色边框,那么我想在第二个工作簿上找到匹配的单元格(范围将始终为列A,第二个工作簿应始终具有匹配值)。

找到匹配项后,我想将值从第一个工作簿(包括格式)返回到找到匹配项的同一行中但在下一个可用列中的第二个工作簿。在大多数情况下,它只是B列,但是如果B列已填充,则移至C列,依此类推。)

match函数起作用,并返回正确的idCella.value。

resultM说找到的匹配行正确,但是我不确定如何继续。

我知道我需要.offset(0,1) resultM,但是我缺少了一些东西,我不确定是什么。

希望说明会有所帮助,但是如果您需要更多信息,请告诉我!

编辑:当我说找到完全匹配时,第二个工作簿上的值将不会具有相同的蓝色border / interior.color。我只想找到cell.value的匹配项。这也许是多余的,但我想我会补充。我还在学习:)。


Dim testWS As Worksheet
Dim testRange As Range,rr2Dest As Range,idCella As Range
Dim alastRow2 As Long,resultM As Long

Set testWS = Workbooks("Test.xlsx").Worksheets("October")                                       'set the 2nd workbook as testWS
Set testRange = testWS.Columns(1)                                                               'searching only column A on testWS (2nd workbook)
alastRow2 = Worksheets("Reruns To Pull").Cells(Rows.Count,"A").End(xlUp).Row                     'find last row in column A that has data on current workbook


For Each idCella In Worksheets("Reruns To Pull").Range("A1:A" & alastRow2).Cells                'for each cell in Column A on current workbook (eventually I want to loop through Column A,D,G,J.  All will be variable ranges)

        If idCella.Borders.Color = RGB(0,192) Then                                                  'On current workbook,if cells in Col A borders.color = blue then

            resultM = Application.Match(idCella.Value,testRange,0)                                        'find exact match on Test.xlsx (2nd workbook) and store in variable resultM
                                                                                                'look up value is the first cell found on current workbook that has blue border
                                                                                                'the range I want to search is column A of Test.xlsx
            Set rr2Dest.Value = resultM                                                                        'trying to set this result to a variable so I can offset the range location by 1 column (Result from current workbook goes to Column B on Tets.xlsx workbook)

            rr2Dest.Value = idCella.Value
            rr2Dest.Interior.Color = idCella.Interior.Color                                                 'everything I want to transfer into Column B on the 2nd workbook
            rr2Dest.Borders.Color = idCella.Borders.Color
            rr2Dest.Borders.Weight = idCella.Borders.Weight
        
        End If
    
Next idCella

End Sub```

解决方法

从rr2Dest开始,使用.End(xlToRight).Column获取下一个空闲单元格,然后更新该单元格的值(以及颜色,重量等)。

https://docs.microsoft.com/en-us/office/vba/api/excel.range.end

,

Set rr2dest = testWS.Range("A" & CStr(resultM)).Offset(0,1)

解决了该问题。没意识到宏没有跟踪它在哪个工作簿上。因此,一旦我指定了它,并与包含匹配项的变量结合使用CStr

只需提出Schutt的答案,那应该很好。