[英]VBA loop through array
我遇到了以下問題:工作簿包含一個名為“名稱”的工作表。 它有姓名和姓氏、eng 姓名、rus 姓名和員工性別以及代碼的列。 該代碼應該從列中獲取值,然后它創建一個 arrays 並循環通過這些 arrays 並且它應該相應地更改另一張表上的值,如員工 1,員工 1 的姓名,...員工 1 的代碼, 員工 2, 員工 2 的姓名, ... 員工 2 的代碼,但它的執行方式如下:員工 1,員工 1 的姓名,... 員工 1 的代碼,員工 1,員工 1 的姓名,.. . 員工 2 的代碼,員工 1,員工 1 的姓名,... 員工 3 的代碼等等。很明顯,我丟失了應該以假定方式生成的代碼,但我找不到它。
代碼如下。 非常感謝您!
Sub SaveAsPDF()
Dim ws As Workbook
Dim nm As Worksheet
Dim last_row As Long
Dim names_surname, name, sex, promocode As Variant
Dim Certificate As Worksheet
Dim FilePath As String
Set ws = ThisWorkbook
Set nm = ws.Sheets("Names")
With nm
last_row = .Range("A1").CurrentRegion.Rows.Count
names_surname = Application.Transpose(nm.Range("E2:E" & last_row).Value2)
name = Application.Transpose(.Range("F2:F" & last_row).Value2)
sex = Application.Transpose(.Range("G2:G" & last_row).Value2)
promocode = Application.Transpose(.Range("H2:H" & last_row).Value2)
End With
Set Certificate = ws.Sheets("Certificate_PDF")
FilePath = "C:\Users\name\folder\2021\Desktop\Certificates"
For Each ns In names_surname
For Each n In name
For Each s In sex
For Each p In promocode
If s = "mr" Then
Certificate.Range("Name").Value = "Dear, " & n & "!"
Else
Certificate.Range("Name").Value = "Dear, " & n & "!"
End If
Certificate.Range("Promo").Value = "Code: " & p
Certificate.PageSetup.Orientation = xlPortrait
Certificate.ExportAsFixedFormat Type:=xlTypePDF, FileName:=FilePath & "\" & ns & ".pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False
Next p
Next s
Next n
Next ns
MsgBox "Completed", vbInformation
End Sub
不要嵌套循環,只需遍歷一個二維數組。
Option Explicit
Sub SaveAsPDF()
Dim wb As Workbook
Dim wsNm As Worksheet, wsCert As Worksheet
Dim last_row As Long
Dim ar As Variant
Dim FilePath As String
Set wb = ThisWorkbook
Set wsNm = wb.Sheets("Names")
With wsNm
last_row = .Cells(.Rows.Count, "E").End(xlUp).Row
ar = .Range("E2:H" & last_row).Value2
End With
Set wsCert = wb.Sheets("Certificate_PDF")
FilePath = wb.Path '"C:\Users\name\folder\2021\Desktop\Certificates"
Dim i As Long, fullname As String, name As String, sex As String, promocode As String
For i = 1 To UBound(ar)
fullname = ar(i, 1) ' E name surname
name = ar(i, 2) ' F
sex = ar(i, 3) ' G
promocode = ar(i, 4) 'H
With wsCert
If sex = "mr" Then
.Range("Name").Value = "Dear, " & name & "!"
Else
.Range("Name").Value = "Dear, " & name & "!"
End If
.Range("Promo").Value = "Code: " & promocode
' export as pdf
.PageSetup.Orientation = xlPortrait
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=FilePath & "\" & fullname & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False
End With
Next
MsgBox UBound(ar) & " pdfs generated", vbInformation
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.