[英]Excel VBA Macros to copy and paste cell value to certain cells based on text in column
我正在尝试基于文本比较将文本值复制并粘贴到Excel中的一定数量的单元格中。
请参阅以下说明:
我有2列A(空白)和B(带值)
在宏之后,将是最终结果:
在检测到Fruits列之后,基本上将底部的单元格作为单元格并将其粘贴到A行中。请注意,到达下一个单元格后,它将获取下一个(底部)单元格值。 F123,F124等
有人可以向我提供excel vba代码吗? 谢谢。
我不会将VBA用于此问题。 我会输入:
=IF(AND(LEFT(B2,1)="F",B2<>"Fruits"),B2,A1)
放入A2并复制下来。 这似乎可以达到您想要的效果。
如果您确实要使用VBA,则经过测试的代码为:
Dim CellValue As String
Dim RowCrnt As Integer
Dim RowMax As Integer
With Sheets("Sheet1") ' Replace Sheet1 by the name of your sheet
RowMax = .Cells(Rows.Count, "B").End(xlUp).Row
For RowCrnt = 2 To RowMax
CellValue = .Cells(RowCrnt, 2).Value
If Left(CellValue, 1) = "F" And CellValue <> "Fruits" Then
.Cells(RowCrnt, 1).Value = CellValue
Else
.Cells(RowCrnt, 1).Value = .Cells(RowCrnt - 1, 1).Value
End If
Next
End With
下面解释了新手可能不了解的上述代码的那些方面。
宏记录器几乎总是使用Range(“ A5”)或Range(“ A5:C10”)来引用范围。
似乎有一些强制使用此格式的命令(对不起,不记得是哪个命令),但对于大多数目的,单元格(行,列)更方便。
如果要在工作表“ Sheet1”的“ A5:C10”范围内的每个数值上加1,则下面显示如何对单元格执行此操作:
Dim CellValue as String
Dim ColCrnt As Integer
Dim RowCrnt As Integer
With Sheets("Sheet1")
For RowCrnt = 5 to 10
For ColCrnt = 1 to 3 ' "A" to "C"
CellValue = .Cells(RowCrnt, ColCrnt).Value
If IsNumeric(CellValue) Then
.Cells(RowCrnt, ColCrnt).Value = CellValue + 1
End If
Next
Next
End With
访问工作表中的单元格会浪费时间,但是我使用CellValue的原因更多,因为太多的单元格引用会使代码变得非常混乱。
注意:在“ A5”中,列位于第一位,而在Cells(5,1)中,该行位于第一位。
您可以使用单元格定义范围。 以下将活动工作表的“ A5:C10”设置为粗体:
Range(Cells(5,1), Cells(10,3)).Font.Bold = True
要解决活动工作表最后一行的A列:
Cells(Rows.Count,"A")
要解决第1行的最后一列:
Cells(1,Columns.Count)
Ctrl + Up,Ctrl + Down,Ctrl + Left和Ctrl + Right可用于从空单元格跳转到具有指示方向值的下一个单元格。 您可以在VBA中执行相同的操作。 但是更有用的是,您可以获得光标将跳至的行或列的值,而不会移动光标。
如果光标位于最后一行的B列中,并按Ctrl + Up,则光标将跳至带有B列中的值的最后一行。以下将RowMax设置为活动工作表的该行号:
RowMax = Cells(Rows.Count, "B").End(xlUp).Row
要获得第27行的最后使用的列:
ColMax = Cells(27,Columns.Count).End(xlToRight).Column
试试我的宏
Option Explicit
Sub test()
Dim My_st$
Dim Ro%, Lr%
With Sheets("Sheet1") ' Replace Sheet1 by the name of your sheet
Lr = .Cells(Rows.Count, "B").End(xlUp).Row
Range("a2").Resize(Lr).ClearContents
For Ro = 2 To Lr
My_st = .Cells(Ro, 2).Value
.Cells(Ro, 1) = _
IIf(My_st Like "[A-Z]#*", My_st, .Cells(Ro - 1, 1))
Next
End With
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.