2010-12-02 167 views
1

我想在Excel行中打印值。我可以到達並選擇它,但我如何循環通過細胞?還是有一個行我可以閱讀的對象?在Excel中打印行單元格值

Range("A1").End(xlUp).Offset(1, 0).Select 

    Do Until IsEmpty(ActiveCell) 

     r = Rows(ActiveCell.Row).EntireRow.Select 

     For Each cell In r.Cells 
      Debug.Print cell.Value 
     Next cell 

    Loop 

回答

2

我覺得這樣做Do Until的IsEmpty(ActiveCell)`是不是一個好主意:
你可以有一些空細胞,然後通過非空單元格。

此代碼如何爲您工作?

Sub print_some_values() 

    Dim c As Long 
    Dim r As Long 
    Dim max_col As Long 

    r = ActiveCell.Row 
    max_col = ActiveSheet.UsedRange.Columns.Count 

    For c = 1 To ActiveSheet.UsedRange.Columns.Count 
     Debug.Print ActiveSheet.Cells(r, c).Value 
    Next c 

End Sub 
+0

猜猜你對空單元格是正確的。 – Lorenzo 2010-12-02 20:49:54

1

我不知道你想達到什麼樣的,但是這個代碼打印當前行,直到空白單元格被發現

Sub a() 

Dim r As Range 
Dim c As Range 

    Set r = Rows(ActiveCell.Row) 
    For Each c In r.Cells 
     If (IsEmpty(c)) Then Exit For 
     Debug.Print c.Value 
    Next c 

編輯

我認爲這是你在找什麼:

Sub a() 

Dim TheArray As Variant 

TheArray = Range("A4:E4").Value 
Debug.Print TheArray(1, 4) 

End Sub 
+0

只是爲了澄清我的用例,我想要遍歷所有行,讀取值並將它們發送到SQL Server。有一個更好的方法嗎?我期望將一行視爲記錄集行,有趣的Excel沒有更好的方式來讀取行中的值。 – Lorenzo 2010-12-02 20:51:57

0

我用混合的方法, 「>」告訴我該行是否髒(已編輯)

Dim r As Range 
Dim c As Range 
Dim max_col As Long 

max_col = ActiveSheet.UsedRange.Columns.Count 

Range("A1").End(xlUp).Offset(1, 0).Select 

Do Until IsEmpty(ActiveCell) 
    Debug.Print ActiveCell.Value 

    If ActiveCell.Value = ">" Then 
     Set r = Rows(ActiveCell.Row) 

     For Each c In r.Cells 
      'print the value of each cell in the row 
      If c.Column = 1 Then 
       'skip 
      ElseIf c.Column <= max_col Then 
       Debug.Print c.Value 
      Else 
       Exit For 
      End If 
     Next c 
    End If 

    ActiveCell.Offset(1, 0).Select 

Loop