簡體   English   中英

用於搜索字符串的 VBA 代碼,如果找到該字符串,則粘貼到另一個工作表中

[英]VBA Code to search a string and if the string is found paste in another worksheet

我正在嘗試編寫一個 VBA 代碼,其中單元格中提到了字符串(search_string 根據代碼)。 我在另一個工作表(MasterRolePLMap)中搜索該字符串,如果字符串匹配,我必須復制整行並將其粘貼到另一個工作表(能力視圖)。 當我嘗試粘貼該值時,會出現調試錯誤“將一個工作表中的所有單元格復制到另一個從 R1c1 開始的工作表”

下面是我的代碼

Sub Click_1()
    Dim key As String
    Dim size As Integer
    row_number = 0
    search_string = Sheets("CompetencyView").Range("B5")
    Sheets("CompetencyView").Activate
    Sheets("CompetencyView").Unprotect Password = "ritu"
    Sheets("CompetencyView").Range("A12").Select
    Do
        If IsEmpty(ActiveCell) = False Then
            Range(ActiveCell, ActiveCell.Offset(0, 11)).Delete shift:=xlUp
        End If
    Loop Until IsEmpty(ActiveCell) = True     'Clearing the previous data
    lastrow = Sheets("MasterRolePLMap").Cells(Rows.Count, 1).End(xlUp).Row    'No of rows in MasterRolePLMap
    Do
        row_number = row_number + 1
        Comp_Name = Sheets("MasterRolePLMap").Range("A" & row_number)
        If InStr(Comp_Name, search_string) > 0 Then
            Sheets("MasterRolePLMap").Rows.Copy
            Sheets("CompetencyView").Activate
            Sheets("CompetencyView").Range("A1").Select
            ActiveSheet.Paste
            Sheets("MasterRolePLMap").Activate
        End If
    Loop Until Comp_Name = ""
End Sub

這里有很多不需要的代碼,您定義了變量但從未使用過它們,然后您使用了從未定義過的變量。

我已經盡我所能清理它,但沒有你的數據來測試我不知道它是否會起作用。

試試這個並報告:

Sub Click_1()
    Dim Comp_Name As String, search_string As String, row_number As Long
    row_number = 0
    search_string = Sheets("CompetencyView").Range("B5")
    Sheets("CompetencyView").Activate
    Sheets("CompetencyView").Unprotect Password = "ritu"
    Sheets("CompetencyView").Range("A12:A" & Range("A" & Rows.Count).End(xlUp).Row).Delete shift:=xlUp
    Do
        row_number = row_number + 1
        Comp_Name = Sheets("MasterRolePLMap").Range("A" & row_number)
        If InStr(Comp_Name, search_string) > 0 Then
            Sheets("MasterRolePLMap").Rows(row_number).Copy 'Changed this to copy the row you need
            Sheets("CompetencyView").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Paste 'I don't think you want to always paste to row 1 as you will just keep overwriting it so I changed it to offset the existing data
        End If
    Loop Until Comp_Name = ""
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM