[英]How to loop macro through a range of cells?
我有一本學校成績練習冊(我是老師)。 我的工作簿中有五張紙,學生輸入他們的用戶名,它將索引匹配所有數據並填寫剩余的表格。
我創建了工作簿的 PDF。 代碼從單元格 C2 中的目標表復制用戶名並將其粘貼到第一表的單元格中,然后填充整個表,然后以用戶名作為文件名導出到 PDF。
如何循環以下部分,使其進入用戶名列表,有效地 C2-C210,一次導出一個 PDF?
我認為下面的代碼需要循環。
'Create and assign variables
Dim Path As String
Dim filename As String
Dim username As String
'.change username value
Sheets("Introduction").Range("B19").Value = Sheets("Target Data").Range("C2").Value
'.create filename
username = Sheets("Target Data").Range("C2").Value
filename = username
Path = "/Users/richard/Desktop/"
'Save active workbook as PDF
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=Path & filename
完整的代碼。
Sub Looptest()
With Sheet2.PageSetup
.CenterHorizontally = True
.CenterVertically = True
.Orientation = xlLandscape
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
With Sheet4.PageSetup
.CenterHorizontally = True
.CenterVertically = True
.Orientation = xlLandscape
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
'Create and assign variables
Dim Path As String
Dim filename As String
Dim username As String
'.change username value
Sheets("Introduction").Range("B19").Value = Sheets("Target Data").Range("C2").Value
'.create filename
username = Sheets("Target Data").Range("C2").Value
filename = username
Path = "/Users/richard/Desktop/"
'Save active workbook as PDF
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=Path & filename
End Sub
我的建議是這樣做
Sub LoopIt()
Dim rgUsernames As Range
Set rgUsernames = Sheets("Target Data").Range("C2:C210")
Dim sngUsername As Range
For Each sngUsername In rgUsernames
Looptest sngUsername.Value2
Next sngUsername
End Sub
上面的代碼將遍歷根據您的帖子在工作表Target Data上Range("C2:C210")
中的用戶名。 Looptest
然后將為每個單個用戶名導出到 PDF 文件。
Sub Looptest(UserName As String)
With Sheet2.PageSetup
.CenterHorizontally = True
.CenterVertically = True
.Orientation = xlLandscape
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
With Sheet4.PageSetup
.CenterHorizontally = True
.CenterVertically = True
.Orientation = xlLandscape
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
'Create and assign variables
Dim Path As String
Dim filename As String
'.change username value
' Sheets("Introduction").Range("B19").Value = Sheets("Target Data").Range("C2").Value
Sheets("Introduction").Range("B19").Value = UserName
'.create filename
' username = Sheets("Target Data").Range("C2").Value
filename = UserName
Path = "/Users/richard/Desktop/"
'Save active workbook as PDF
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=Path & filename
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.