VBA循环遍历数组
Posted
技术标签:
【中文标题】VBA循环遍历数组【英文标题】:VBA loop through array 【发布时间】:2022-01-22 03:35:03 【问题描述】:我遇到了以下问题:工作簿包含一个名为“名称”的工作表。它有姓名和姓氏、eng 姓名、rus 姓名和员工性别以及代码的列。代码应该从列中获取值,然后它创建一个数组并循环遍历这些数组,它应该相应地更改另一张表上的值,例如员工 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
【问题讨论】:
【参考方案1】:不要嵌套循环,只循环一个二维数组。
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
【讨论】:
完美运行!非常感谢!以上是关于VBA循环遍历数组的主要内容,如果未能解决你的问题,请参考以下文章