我是新手,也是VBA的新手。
一直在尝试,发现我可以完全解决循环问题。
我有一个很长的宏来运行它找到一个工作簿并将数据复制到word上的邮件合并中。我无法找到一种方法来循环这个宏,因为我使用A2中的值来查找文件,并需要它循环到A列。
感谢任何帮助。
这是我到目前为止所做的。
Sub OpenWorkbook()
Application.ScreenUpdating = False
varCellvalue = Range("A2").Value
Workbooks.Open("Y:\SHARED_SERVICES\File storage\" & varCellvalue & "\" & varCellvalue & "_preparation v3.xls").Activate
ActiveWindow.Visible = True
Range("A2:AY2").Select
Selection.Copy
ActiveWindow.Close
Windows("Test.xlsm").Activate
Range("B2").Select
ActiveSheet.Paste
Application.CutCopyMode = False
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = False
WordApp.documents.Open("C:\Users\letter Merge trial.docm").ActivateWordApp.Run "MailMergeLetter"
WordApp.ActiveDocument.SaveAs ("Y:\SHARED_SERVICES\File storage\" & varCellvalue & "\Letter_" & varCellvalue & ".doc")
WordApp.ActiveDocument.SaveAs ("C:\Letters to print\Letter_" & varCellvalue & ".doc")
WordApp.ActiveDocument.Close
WordApp.documents("C:\Users\Spreadsheets to merge\ letter Merge trial.docm").Activate
WordApp.ActiveDocument.Close
WordApp.documents.Open("C:\Users\Spreadsheets to merge\ATIP.docx").Activate
WordApp.Run "MailMergeATIP"
WordApp.ActiveDocument.SaveAs ("Y:\SHARED_SERVICES\File storage\" & varCellvalue & "\ATIP_" & varCellvalue & ".doc")
WordApp.ActiveDocument.SaveAs ("C:\Users\Letters to print\ATIP_" & varCellvalue & ".doc")
WordApp.ActiveDocument.Close
WordApp.documents("C:\Users\Spreadsheets to merge\ATIP.docx").Activate
WordApp.ActiveDocument.Close
Windows("Test.xlsm").Activate
End Sub
答案 0 :(得分:1)
我假设列A包含文件夹名称,每个文件夹包含相同的文件(_preparation v3.xls
)名称。
这是循环一系列值的一种方法。
Sub OpenWorkbook()
Application.ScreenUpdating = False
Dim rng As Range
'Change your range according to your list size
Set rng = Range("A2:A10")
For Each cell In rng
varCellvalue = cell
'Put the rest of your code here for looping
'....
Next cell
Application.ScreenUpdating = True
End Sub