我希望在第一列中搜索特定單詞的文本,當找到它們時,將相鄰列復制并粘貼到其他地方。
我有這個代碼,如果文本正是這些單詞,它可以正常作業,但如果還有其他內容,它就會失敗(即超級合并器)。
我對 VBA 還是很陌生,剛剛修改了一些其他代碼來達到這一點。我認為 find 函式是一個很好的方法,但我無法圍繞如何避免無限回圈。任何幫助在這里將不勝感激
Sub Test()
Dim lr As Long
Dim r As Long
' Find last row in column A with data
lr = Cells(Rows.Count, "A").End(xlUp).Row
' Loop through all rows in column A
For r = 1 To lr
' Check value on entry
If (Cells(r, "A") = "Super") Or (Cells(r, "A") = "Pension") Or (Cells(r, "A") = "SMSF") Then
' Copy column B and paste in C where found
Cells(r, "B").Select
Selection.Copy
ActiveCell.Offset(0, 1).PasteSpecial
End If
Next r
End Sub
uj5u.com熱心網友回復:
您要查找的內容稱為通配符字串比較。您可以使用 VBA 的Like 運算子來實作您的輸出
If (Cells(r, "A") Like "Super*") Or (Cells(r, "A") Like "Pension*") Or (Cells(r, "A") Like "SMSF*") Then
這里的*inSuper*意味著文本應該以“Super”開頭,之后可以有任何內容。
如果您想搜索單元格是否在任何地方包含“超級”,您可以使用*Super*-*在Super
uj5u.com熱心網友回復:
為了獲得更健壯的代碼,我將您正在檢查的“信號”字移動到子開頭的陣列中。
與要復制的列的列索引和目標索引相同。
如果需求發生變化,那么進行調整就容易多了,例如尋找第四個詞等。
此外,您應該避免隱式參考單元格。這就是我添加 ws 變數的原因 - 您必須調整作業表名稱。
另外,我添加了一個通用函式isInArray,該函式采用單元格值加上具有查找值的陣列并回傳 true 或 false。這里like實作了-operator。
你并不需要選擇復制/粘貼值-你可以簡單地把它們寫入到目標小區:.Cells(r, targetColumnIndex).value = .Cells(r, sourceColumnIndex).value。
但請注意:如果您有大量資料,將所有內容加載到陣列中并進行處理會更有意義……但這是下一個要學習的課程;-)
Option Explicit
Public Sub copyValues()
Dim arrLookupValues(2) As Variant
arrLookupValues(0) = "Super"
arrLookupValues(1) = "Pension"
arrLookupValues(2) = "SMSF"
Const sourceColumnIndex As Long = 2 'take value from column B
Const targetColumnIndex As Long = 3 'write value to colum C
application.screenupdating = false
Dim lr As Long
Dim r As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1") 'adjust this to your needs
With ws
lr = .Cells(.Rows.Count, "A").End(xlUp).Row
For r = 1 To lr
' Check value on entry
If isInArray(.Cells(r, 1).value, arrLookupValues) Then
' write value of column B (2) to C (3)
.Cells(r, targetColumnIndex).value = .Cells(r, sourceColumnIndex).value
End If
Next r
End With
application.screenupdating = true
End Sub
Private Function isInArray(value As Variant, arrLookFor As Variant) As Boolean
Dim i As Long
For i = LBound(arrLookFor) To UBound(arrLookFor)
If value like arrLookFor(i) & "*" Then
isInArray = True
Exit For
End If
Next
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/313351.html
