VBA Iterate through a table



我正在尝试遍历一个经过筛选的表,并打印3列的值。我想让他们把每一行打印成一套(供应商、工厂、价格(。这是我目前掌握的代码。

For Each Row In Union(Range("TblRawData[Supplier]"), Range("TblRawData[plant]"), Range("TblRawData[price]")).Rows
If Row.EntireRow.Hidden = False Then
Debug.Print Row.Value
End If
Next Row

这个代码打印所有的供应商,然后是所有的工厂,然后是价格。而不是每一行都是一个集合。

Code Results:        Desired Result:
supplier1            supplier1, plant1, $1.50
supplier2            supplier2, plant2, $2.00
supplier3            supplier3, plant3, $3.00
plant1
plant2
plant3
$1.50
$2.00
$3.00

这种方法使用ListRows和简单的变量构造对我有效。

(在这种情况下,请原谅abc变量名(

Option Explicit
Sub printRows()
Dim rawData As ListObject
Set rawData = Worksheets("Sheet1").ListObjects("TblRawData") 'change sheet name as needed
Dim lr As ListRow
For Each lr In rawData.ListRows
If lr.Range(1, 1).EntireRow.Hidden = False Then
Dim a As String, b As String, c As String
a = lr.Range(1, rawData.ListColumns("Supplier").Index).Value
b = lr.Range(1, rawData.ListColumns("plant").Index).Value
c = Format(lr.Range(1, rawData.ListColumns("price").Index).Value, "$#,###.00")
Dim output As String
output = a & ", " & b & ", " & c
Debug.Print output
End If
Next
End Sub

Debug.Print隐式写入回车/"新行"。您需要在循环中使用(;(控制字符来防止它——使用逗号(,(,您可以将值与表格对齐(无需实际输出逗号(:

Debug.Print Row.Value,; '<~ that semicolon is important!

并且在每个新的Row:

Debug.Print '<~ no semicolon will append the carriage return so next iteration outputs to a new line

换句话说:

For Each Row In Union(Range("TblRawData[Supplier]"), Range("TblRawData[plant]"), Range("TblRawData[price]")).Rows
If Row.EntireRow.Hidden = False Then
Debug.Print Row.Value,;
End If
Debug.Print
Next Row

应该输出这样的东西:

supplier1      plant1    $1.50
supplier2      plant2    $2.00
supplier3      plant3    $3.00

最新更新