我试图在VBA中创建一个CSV输出文件,但我似乎无法得到它。我需要遍历电子表格并从列中提取数字'我'基于列D是否具有" 1"在它与否。然后我想粘贴列的内容'我'进入专栏' A' CSV输出文件。有人可以帮我完成这个吗?我想整合以下所有内容:
Sub Test()
Dim FileNum, bOutputLine, bFile As String
Dim bOUTPUT, iRow As Integer
bOUTPUT = FreeFile 'Define bOUTPUT as a FreeFile
bFile = "C:\Desktop\Test.csv" 'set the filepath equal to a string
For iRow = 2 To ActiveSheet.UsedRange.Rows.Count
If Trim(range("D" & iRow)) <> "" Then
FileNum = Trim(range("I" & iRow))
End If
Next
Open bFile For Output As bOUTPUT 'Open the file
bOutputLine = FileNum
Print #bOUTPUT, bOutputLine
Close #bOUTPUT 'Close the file
End Sub
答案 0 :(得分:2)
您需要将文件交互放在for-next循环中并打开作为append而不是output,或者在循环中构建一个将在底部打印出来的字符串变量。以下是两个选项:
Sub Test()
Dim FileNum, bOutputLine, bFile As String
Dim bOUTPUT, iRow As Integer
bOUTPUT = FreeFile 'Define bOUTPUT as a FreeFile
bFile = "C:\Users\HPUser\Desktop\Test.csv" 'set the filepath equal to a string
Open bFile For Append As bOUTPUT 'Open the file
For iRow = 2 To ActiveSheet.UsedRange.Rows.Count
If Trim(range("D" & iRow)) <> "" Then
FileNum = Trim(range("I" & iRow))
bOutputLine = FileNum
Print #bOUTPUT, bOutputLine
End If
Next
Close #bOUTPUT 'Close the file
End Sub
或
Sub Test()
Dim FileNum, bOutputLine, bFile As String
Dim bOUTPUT, iRow As Integer
bOUTPUT = FreeFile 'Define bOUTPUT as a FreeFile
bFile = "C:\Users\HPUser\Desktop\Test.csv" 'set the filepath equal to a string
For iRow = 2 To ActiveSheet.UsedRange.Rows.Count
If Trim(range("D" & iRow)) <> "" Then
bOutputLine = bOutputLine & Trim(range("I" & iRow)) & vbcrlf
End If
Next
Open bFile For Output As bOUTPUT 'Open the file
Print #bOUTPUT, bOutputLine
Close #bOUTPUT 'Close the file
End Sub
答案 1 :(得分:1)
一种方法是直接在循环中写入:
Open bFile For Output As bOUTPUT
For iRow = 2 To ActiveSheet.UsedRange.Rows.Count
If InStr(1, Range("D" & iRow), "1") <> 0 Then
Print #bOUTPUT, Trim(Range("I" & iRow))
End If
Next
Close #bOUTPUT
InStr
将在D列的单元格中查找值“1”(如问题的措辞,似乎它可能类似于“AAA1A”。如果“1”不是,则返回0找到。