簡體   English   中英

VBA 遍歷一個表

[英]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隱式寫入一個回車符/“新行”。 你會想在這里使用 ( ; ) 控制字符,在循環內,以防止它 - 使用逗號 ( , ) 你可以將值與表格對齊(實際上不需要 output 一個逗號):

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

output 應該是這樣的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM