Arun Solomon
Arun Solomon

Reputation: 421

loop on the rows in excel vba

I need help in Excel. My question is: How can I get the first row of each row in this loop and print the output.

Input Column and Row value is like this:

    col1  col2   col3

    1    test    abc

    2    tests   dfg

    3    gtd     gdd

Output like this.

(col1,col2,col3)('1','test','abc');
(col1,col2,col3)('2','tests','dfg');
(col1,col2,col3)('3','gtd','gdd');

The Code that I am working on is

    For i = 1 To LastRow
        For j = 3 To LastCol
            If IsNumeric(Cells(i, j)) & Cells(i, j) > 0 = True Then
              vaString = vaString & Cells(i, j)
            End If
            If j <> LastCol Then vaString = vaString & ","
            If j = LastCol Then vaString = vaString
        Next j
            myString = myString                  
    Next i

Thanks in advance

Upvotes: 0

Views: 130

Answers (2)

bluk
bluk

Reputation: 410

From your parameters I will assume your data starts from cell C1. Change the first few lines if otherwise.

Sub Testing()
Dim FirstRow As Integer, FirstCol As Integer, LastRow As Integer, LastCol As Integer
FirstRow = 1
FirstCol = 3
LastRow = 4
LastCol = 5

Dim arrStr() As String
Dim strFirstRow As String
Dim strPath As String
strPath = "C:\..." ' Path of your choice
Open strPath For Append As #1

ReDim arrStr(FirstCol To LastCol)
For j = FirstCol To LastCol
    arrStr(j) = CStr(Cells(FirstRow, j))
Next j
strFirstRow = "(" & Join(arrStr, ",") & ")"

For i = FirstRow + 1 To LastRow
    If IsNumeric(Cells(i, FirstCol).Value) Then
        If Cells(i, FirstCol).Value > 0 Then
            ReDim arrStr(FirstCol To LastCol)
            For j = FirstCol To LastCol
                arrStr(j) = "'" & CStr(Cells(i, j)) & "'" 
            Next j
            Debug.Print strFirstRow & "(" & Join(arrStr, ",") & ");"
            Print #1, strFirstRow & "(" & Join(arrStr, ",") & ");"
        End If
    End If
Next i
Close #1
End Sub

Upvotes: 1

JvdV
JvdV

Reputation: 75850

Here is a rather simple example making use of array variables:

Sub Test()

Dim x As Long
Dim str1 As String, str2 As String
Dim arr1() As Variant, arr2() As Variant

With ThisWorkbook.Sheets("Sheet1") 'Change according to your sheetname
    arr1 = Application.Transpose(Application.Transpose(.Range("A1:C1").Value2))
    arr2 = .Range("A2:C" & .Cells(.Rows.Count, "A").End(xlUp).Row).Value2
    str1 = "(" & Join(arr1, ",") & ")"
    For x = LBound(arr2) To UBound(arr2)
        str2 = "(" & Join(Array(arr2(x, 1), arr2(x, 2), arr2(x, 3)), ",") & ")" & ";"
        Debug.Print str1 & str2 'Do something with the full string
    Next x
End With

End Sub

enter image description here

Upvotes: 0

Related Questions