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
452 views
in Technique[技术] by (71.8m points)

excel - VBA, For Each Next - If sheet name in this workbook equals to a sheet name in another workbook

I have two workbooks, some sheets have the same name. I would like to export (copy) some data from sheet A in Workbook TeamINSO to this workbook (where the code is) to the sheet with the same name and I'm stuck. How to write: loop through sheets in workbook TeamINSO, if sheet name equals a sheet name in this workbook, then copy range?

For Each ws In TeamINSO.Worksheets
    If ws.Name = ThisWorkbook.Worksheets(ws.Name) Then
        Workbooks(TeamINSO).Worksheets(ws.Name).Range("A3:C400").Copy
               ThisWorkbook.Worksheets(ws.Name).Range("A2").PasteSpecial xlPasteValues
    Else
    End If
Next ws

Thanks for helping.

question from:https://stackoverflow.com/questions/65891772/vba-for-each-next-if-sheet-name-in-this-workbook-equals-to-a-sheet-name-in-an

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

1 Reply

0 votes
by (71.8m points)

You can do it like this:

Dim ws As Worksheet, wsD as Worksheet

For Each ws In TeamINSO.Worksheets
    'see if there's a match
    On Error Resume Next  'ignore error if no match
    Set wsD = ThisWorkbook.Sheets(ws.Name)
    On Error Goto 0       'stop ignoring errors
    'any match?
    If Not wsD Is Nothing Then
        'Transfer values 
        With ws.Range("A3:C400")
          wsD.Range("A2").Resize(.Rows.Count, .Columns.Count).Value = .Value
        End With
    End If

    Set wsD = Nothing 'set up for next iteration if any
Next ws

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

...