简体   繁体   中英

Search for specific string format using VBA and paste to a new excel worksheet

I am attempting to consolidate some data into a specific excel template I have created. My data is titled as PAxxx.xx where x could be any number between 0-9. Is there a way I can search through my current workbook for that specific title "PAxxx.xx" and populate it into my created template field.

I current have this search function in VBA:

Sub CopyPasteCellData()

Dim FirstAddress As String
Dim searchTerms As Variant
Dim Rcount As Long
Dim I As Long
Dim Rng As Range

Dim currentWorkbook As Workbook
Dim newWorkbook As Workbook
Dim currentWorksheet As Worksheet
Dim newWorksheet As Worksheet

Set currentWorkbook = Workbooks("LVX Release 2015 (2).xlsm")
Set currentWorksheet = currentWorkbook.Sheets("PA5179.01")

Set newWorkbook = Workbooks("Test.xlsx")
Set newWorksheet = newWorkbook.Sheets("Sheet1")

'newWorksheet.Range("C2").Value = currentWorksheet.Range("A1").Value

searchTerms = Array("PA")

With currentWorksheet.UsedRange
    Rcount = 0
    For I = LBound(searchTerms) To UBound(searchTerms)
        Set Rng = .Find(What:=searchTerms(I), _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
            If Not Rng Is Nothing Then
                FirstAddress = Rng.Address
                Do
                    Rcount = Rcount + 1
                    newWorksheet.Range("A" & Rcount).Value = Rng.Value
                    Set Rng = .FindNext(Rng)
                Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
            End If
    Next I
End With              
End Sub 

Just not sure how to search the sheet for all data sets PAxxx.xx.

Thanks in advance :)

Here is a basic principle how to loop through all the sheets and find for a PAxxx.xx -> read instructions of Like operator if you need to change the validation ->

Sub LoopTroughWorkSheetsAndFindPA()
Dim wb As Workbook: Set wb = ThisWorkbook 'anyreference of a workbook you want
Dim ws As Worksheet

For Each ws In wb.Worksheets
    If ws.Name Like "PA###.##" Then
        'do some operations here for example ->
        Debug.Print ws.Name
    End If
Next

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM