简体   繁体   English

在Excel VBA中的行上循环

[英]loop on the rows in excel vba

I need help in Excel. 我在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 提前致谢

From your parameters I will assume your data starts from cell C1. 根据您的参数,我将假定您的数据从单元格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

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM