繁体   English   中英

VBA循环打印到CSV输出

[英]VBA Loop Print to CSV Output

我正在尝试在VBA中创建CSV输出文件,但似乎无法获取它。 我需要遍历电子表格,并根据D列中是否有“ 1”来从“ I”列中提取数字。 然后,我想将列“ I”的内容粘贴到CSV输出文件的列“ A”中。 有人可以帮我完成这个吗? 我想合并以下所有内容:

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

您需要将文件交互放置在for-next循环中,并以append而不是输出方式打开,或者在循环中构建一个字符串变量,该变量将在底部显示。 这是两个选项:

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

一种方法是直接在循环中写入它:

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。

暂无
暂无

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

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