下面是我的宏代码,只有一个问题是每次我们将导出该文件名称的转储每次都会被更改。
结束号码将始终更改:"SECONDARY MIS MODULE (11)"
,"SECONDARY MIS MODULE (12)"
等
Sub MySub
a = 6
b = 2
Do While Workbooks("segment.xlsm").Worksheets("Sheet4").Cells(b, 1) <> ""
Z = WorksheetFunction.SumIf(Workbooks("SECONDARY MIS MODULE (11).xlsx").Worksheets("SECONDARY MIS MODULE (11)").Range("B5:K5"), _
"FRANCHISEE DEVELOPMENT", Workbooks("SECONDARY MIS MODULE (11).xlsx").Worksheets("SECONDARY MIS MODULE (11)").Range(Cells(a, 2), Cells(a, 11)))
x = Application.SumIf(Workbooks("SECONDARY MIS MODULE (11).xlsx").Worksheets("SECONDARY MIS MODULE (11)").Range("B5:K5"), _
"PRIVATE WEALTH GROUP", Workbooks("SECONDARY MIS MODULE (11).xlsx").Worksheets("SECONDARY MIS MODULE (11)").Range(Cells(a, 2), Cells(a, 11)))
Workbooks("segment.xlsm").Worksheets("Sheet4").Cells(b, 13).Value = x + Z
a = a + 1
b = b + 1
Loop
End Sub
答案 0 :(得分:0)
如果我理解正确,您希望能够在多个工作簿/工作表上应用此代码。您只需添加工作簿名称和/或工作表名称作为方法的参数:
Sub MySub(wbName As String, wsName As String)
a = 6
b = 2
Do While ' ......
Z = WorksheetFunction.SumIf(Workbooks(wbName).Worksheets(wsName).Range("B5:K5"), _
"FRANCHISEE DEVELOPMENT", Workbooks(wbName).Worksheets(wsName).Range(Cells(a, 2), Cells(a, 11)))
'
'
'
Loop
End Sub
<强>用法:强>
For i = 11 To 15
MySub "SECONDARY MIS MODULE (" & i & ").xlsx", "SECONDARY MIS MODULE (" & i & ").xlsx"
Next
更新1:
如果您不知道工作簿名称的数字部分,可以编写一个返回实际工作簿名称的辅助函数,如下所示:
Function GetWorkbookNameByPartial(pattern As String) As String
For Each wb In Workbooks
If wb.Name Like pattern Then
GetWorkbookNameByPartial = wb.Name
Exit Function
End If
Next
End Function
<强>用法:强>
Dim wbName As String
wbName = GetWorkbookNameByPartial("SECONDARY MIS MODULE (*).xlsx")
If Len(wbName) > 0 Then
MySub wbName, wbName ' Only if worksheet name matches workbook name.
' Otherwise, you will need to change worksheet name.
End If
希望有所帮助:)