[英]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.