用工作簿中的值替换选择

时间:2020-08-18 17:29:34

标签: excel vba

我试图用另一本的偏移值替换我在一个工作簿上的选择。

我使用的代码是:

Sub NameUpdate()
Dim cCell As Range, cRange As Range, sCell As Range, sRange As Range
Dim cLastRow As Long
Dim FindString As String
Dim wb As Workbook, sup As Worksheet
Set wb = Workbooks("MyWorkbook.xlsm")
Set sup = wb.Worksheets("Codes")
cLastRow = sup.Cells(Rows.Count, "A").End(xlUp).Row
Set cRange = sup.Range("A2:B" & cLastRow)
Set sRange = Selection
For Each sCell In sRange
   FindString = sCell.Value
   For Each cCell In cRange
      If cCell.Value = FindString Then
         sCell.Value = cCell.Offset(0, 1).Value
     End If
   Next cCell
Next sCell
End Sub

我试图结合两个对我有用的宏,但是我似乎无法让它们一起工作。它不会给我错误,但是运行时却什么也没做。 Google并没有帮助,但是有可能是因为我不知道我在寻找什么或在做什么。希望这里有人可以帮助我。谢谢!

1 个答案:

答案 0 :(得分:0)

代码很好,这是用户错误。目标细胞中有一个空间。

添加了sCell.Value = Trim(sCell.Value)

将代码更改为:

Sub NameUpdate()
Dim cCell As Range, cRange As Range, sCell As Range, sRange As Range
Dim cLastRow As Long
Dim FindString As String
Dim wb As Workbook, sup As Worksheet
Set wb = Workbooks("MyWorkbook.xlsm")
Set sup = wb.Worksheets("Codes")
cLastRow = sup.Cells(Rows.Count, "A").End(xlUp).Row
Set cRange = sup.Range("A2:B" & cLastRow)
Set sRange = Selection
For Each sCell In sRange
sCell.Value = Trim(sCell.Value)
FindString = sCell.Value
For Each cCell In cRange
If cCell.Value = FindString Then
sCell.Value = cCell.Offset(0, 1).Value
End If
Next cCell
Next sCell
End Sub

现在工作正常,抱歉!