Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

VBA Excel Set Workbook with name like something

I have a situation, in which my code needs to be referred to the external workbook, which has been created just recently. Therefore it doesn’t have a generic name. Because the name is default it always comes as Book1, Book2, Book3, etc.

I found a nice hint here:

VBA recognizing workbook by partial name

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And applied to my situation like below:

 Dim mwkt As Workbook, pwkt As Workbook
 Dim wbName As String
 wbName = "Book"
 For Each pwkt In Application.Workbooks
 If pwkt.Name Like wbName & "*" Then
 Set pwkt = pwkt.Name
 End If
 Next pwkt

  Set pwkt = pwkt.Name  retiurns the **'Type mismatch'** error.

Is there any way of sirting this out?

>Solution :

‘pwkt.Name’ will return a String but you have declared pwkt as a Workbook. That is the type mismatch.

You are also using the variable pwkt for the loop and also for the setting within the loop. Perhaps you mean something like this?

Dim mwkt As Workbook, pwkt As Workbook, wb as Workbook
Dim wbName As String
wbName = "Book"
For Each wb In Application.Workbooks
    If wb.Name Like wbName & "*" Then
        Set pwkt = wb
    End If
Next wb
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading