在excel vba中的行上循环
我需要Excel的帮助。我的问题是:如何获取循环中每行的第一行并打印输出 输入的列和行值如下所示:在excel vba中的行上循环,excel,vba,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'
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
下面是一个使用数组变量的简单示例:
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
布拉克,谢谢你,这很有效。有没有办法像新的更新问题中那样添加单引号?还有,如何将值写入txt文件?你能帮我吗