Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

excel - Search for sheets' name if matched condition then copy paste value with format?

Update: I was able to solve this problem. I just remembered VBA use * and ? to present the string 'If Sheet.name Like "*CopyA"'


I would like to make a copy special value with original format of the sources of all sheets contains the word: "CopyA" for example "Apple CopyA","Mango CopyA"

I can use the macro record to see how VBA create sheet and copy special like similar example below.

I am having trouble in the searching for sheet name - All examples I found either I must know exact name (same as Macro record) or I have to make a copy of all sheets (loop though all sheet and copy, no matter the name is).

Sub Macro1()
    Sheets("Sheet1").Select
    Sheets("Sheet1").Copy Before:=Sheets(1)
    Sheets("Sheet1(2)").Select
    Cells.Select
    Selection.Copy
    ActiveSheet.Paste
    Application.CutCopyMode = False
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
End Sub

How can I search for sheet's name? In this case, any sheet that has "CopyA"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another way :) You can also use Instr(). For example

For all sheets in the workbook, use this

Option Explicit

Sub Macro1()
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Sheets
        If InStr(1, ws.Name, "CopyA") Then
            '~~ > Your code
        End If
    Next
End Sub

For ActiveSheet use this

Option Explicit

Sub Macro1()
    If InStr(1, ActiveSheet.Name, "CopyA") Then
        '~~ > Your code
    End If
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...