将单元格的值剪切并粘贴到vba中的另一个单元格
Posted
技术标签:
【中文标题】将单元格的值剪切并粘贴到vba中的另一个单元格【英文标题】:Cut and paste the value of cell to another cell in vba 【发布时间】:2018-10-23 14:27:50 【问题描述】:如果 C 列等于“RRR”,我需要将 F 列的值转移或移动,直到最后一个具有值的单元格到 D 列。我无法突出显示或选择从“RRR”位置开始到值为“SSS”的最后一个单元格的范围。相反,它从 C4:C9 中选择范围,这是错误的。
Dim ws As Worksheet, lRow As Long
Set ws = ThisWorkbook.ActiveSheet
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
Dim lCol As Long
With ws
For x = 1 To lRow
If .Cells(x, 3).Value = "RRR" Then
lCol = Cells(x, Columns.Count).End(xlToLeft).Column
Range("C" & x & ":C" & lCol).Select
End If
Next x
End With
示例:
预期:
谁能告诉我代码中的问题。
【问题讨论】:
这不起作用的原因:Range("C" & x & ":C" & lCol).Select
是因为您说,范围应该从(C 列和 x 行,即 C4)到(C 列和相等的行重视 lCol 给你,即 C9)
【参考方案1】:
你已经很近了,只有应该修改的选择范围。
所以你可以建立你的范围:
Range(A1:D1) -> Range(Cells(A1), Cells(D1)) ->
Range(Cells(row number, column number), Cells(row number, column number)) ->
Range(Cells(1, 1), Cells(1, 4))
这应该可以解决问题:
Dim ws As Worksheet, lRow As Long
Dim x As Long
Set ws = ThisWorkbook.ActiveSheet
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
Dim lCol As Long
With ws
For x = 1 To lRow
If .Cells(x, 3).Value = "RRR" Then
lCol = Cells(x, Columns.Count).End(xlToLeft).Column 'Find the last column number
Range(Cells(x, 6), Cells(x, lCol)).Cut Cells(x, 4) 'Cut from row x and Column F (Column F = 6) to row x and column "lCol". Then paste the range into row x and column 4.
End If
Next x
End With
End Sub
【讨论】:
不客气,谢谢!!!,你做了大部分工作:)!!我想给你最后一个建议。声明所有变量(未声明 x)。一个好习惯是让VBA强制变量,那就不能错过了。 How do I force VBA/Access to require variables to be defined?。当您编码时,它将对您有很大帮助:)。祝你好运,编码愉快:D!!【参考方案2】:另一种方法是删除D
和E
列中的单元格
Dim ws As Worksheet, lRow As Long
Dim x As Long
Set ws = ThisWorkbook.ActiveSheet
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
Dim lCol As Long
With ws
For x = 1 To lRow
If .Cells(x, 3).Value = "RRR" Then .Range("C" & x & ":D" & x).Delete Shift:=xlToLeft
End If
Next x
End With
End Sub
【讨论】:
非常感谢。以上是关于将单元格的值剪切并粘贴到vba中的另一个单元格的主要内容,如果未能解决你的问题,请参考以下文章