Excelmacros只在某些工作簿首先打开时才起作用

我有一个macros的Excel在三个工作簿之间传输数据。 两个工作簿保持不变,只是模板。 第三本工作手册是业务pipe理系统的输出。 它会改变,但始终以“RFQ_”开始。 例如; RFQ_14787,RFQ_14839,RFQ_63528。

下面的代码是通过打开的工作簿循环编写的,select以“RFQ_”开头的代码,并将该名称存储在整个代码中要使用的variables中。

在testing这个代码时,我发现它只有在名为“RFQ_XXXXX”的工作簿首先打开时才有效。

代码的所有功劳都归于@Tim Williams,他的回答是我的其他问题之一。

Sub Tester2() Dim wbName As String, shtSrc As Worksheet, shtDest As Worksheet wbName = GetRfqWbName("RFQ_") If Len(wbName) = 0 Then MsgBox "Didn't find the RFQ workbook!" Exit Sub Else 'for example: you can substitute the sheet names instead Set shtSrc = Workbooks(wbName).Sheets(1) Set shtDest = Workbooks("Transfer Template.xlsm").Sheets(1) End If shtSrc.Range("J51").Copy shtDest.Range("B1") End Sub 'get the name of the first workbook which begins with sName... Function GetRfqWbName(sName As String) As String Dim wb As Workbook For Each wb In Workbooks If wb.Name Like sName & "*" Then GetRfqWbName = wb.Name Exit For Next wb End Function 

我只是在寻找一个解释,出于好奇,但如果有人有办法运行macros而不打开“RFQ_”工作簿,我将不胜感激。

不幸的是,我不允许发表评论,所以我不得不作出这个答案,但像我看到的问题是在:

 For Each wb In Workbooks If wb.Name Like sName & "*" Then GetRfqWbName = wb.Name Exit For Next wb 

Exit For不是if语句的一部分,所以在第一个工作簿被检查后每次都会打开循环 – 无论是否成功…

编辑 :如下更改代码来解决问题

 For Each wb In Workbooks If wb.Name Like sName & "*" Then GetRfqWbName = wb.Name Exit For End If Next wb