excel - 在excel vba中的行上循环
问题描述
我需要 Excel 帮助。我的问题是:如何获取此循环中每一行的第一行并打印输出。
输入列和行值是这样的:
col1 col2 col3
1 test abc
2 tests dfg
3 gtd gdd
像这样输出。
(col1,col2,col3)('1','test','abc');
(col1,col2,col3)('2','tests','dfg');
(col1,col2,col3)('3','gtd','gdd');
我正在编写的代码是
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
提前致谢
解决方案
根据您的参数,我将假设您的数据从单元格 C1 开始。如果不是,请更改前几行。
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