vba +将值写入动态一维数组并写入csv文件

时间:2015-02-01 20:55:08

标签: arrays vba excel-vba csv excel

将数组写入.csv文件时遇到问题。我找到了一种方法来创建一个数组并将其写入.csv文件,但它给出了一个错误@(arrayNumber(i)= mainWorkBook.Sheets(“Sheet1”)。范围(“A”& i).Value )。我找不到为什么我不能将这些值写入数组。由于这个问题,我也无法测试.Csv文件的写入是否正确。我希望有人能指出我正确的方向。提前谢谢。

Sub Numbering()

Dim arrayNumber()
Dim arrayName()

Dim pathName As String

If ActiveSheet.Name = "OVERVIEW" Or ActiveSheet.Name = "Template" Or ActiveSheet.Name = "Develop" Or ActiveSheet.Name = "Schedule" Or ActiveSheet.Name = "Information" Or ActiveSheet.Name = "Announcements" Or ActiveSheet.Name = "Database" Then
    MsgBox ("You can't extract the number and name to a csv file.")

Else

    pathName = "C:" & "\textfile.csv"
    Open pathName For Output As #1
    Print #1, "Number   Name"

    ActiveSheet.Select
    LastRow = ActiveSheet.Range("K1048555").End(xlUp).Row
    ReDim Preserve arrayNumber(1 To LastRow)
    ReDim Preserve arrayName(1 To LastRow)

    j = 1
    For i = 13 To LastRow

            If ActiveSheet.Range("K" & i).Value = "1" Then
                arrayNumber(i) = mainWorkBook.Sheets("Sheet1").Range("A" & i).Value
                arrayName(i) = ActiveSheet.Range("Q" & i).Value
                Print #1, " arrayNumber & "; " & arrayName"
                j = j + 1
            End If
    Next
    Close #1
    MsgBox ("Done")

End If

End Sub

2 个答案:

答案 0 :(得分:0)

经过一些尝试,我找到了解决方案(下面的代码)。

Sub Numbering()

Dim arrayNumber()
Dim arrayName()

Dim pathName As String

If ActiveSheet.Name = "OVERVIEW" Or ActiveSheet.Name = "Template" Or ActiveSheet.Name = "Develop" Or ActiveSheet.Name = "Schedule" Or ActiveSheet.Name = "Information" Or ActiveSheet.Name = "Announcements" Or ActiveSheet.Name = "Database" Then
    MsgBox ("You can't extract the number and name to a csv file.")

Else

    pathName = "C:" & "\textfile.csv"
    Open pathName For Output As #1
    Print #1, "Number   Name"

    ActiveSheet.Select
    LastRow = ActiveSheet.Range("K1048555").End(xlUp).Row
    ReDim Preserve arrayNumber(1 To LastRow)
    ReDim Preserve arrayName(1 To LastRow)

    j = 1
    For i = 13 To LastRow

            If ActiveSheet.Range("K" & i).Value = "1" Then
               arrayNumber(j) = ActiveSheet.Range("A" & i).Value
                arrayName(j) = ActiveSheet.Range("Q" & i).Value

                MsgBox (arrayNumber(j))
                MsgBox (arrayName(j))
                Print #1, arrayNumber(j) & "; " & arrayName(j)
                j = j + 1
            End If
    Next
    Close #1
    MsgBox ("Done")

End If

End Sub

答案 1 :(得分:0)

你可能会考虑:

Sub M_snb()
  createobject("scripting.filesystemobject").createtextfile("C:\textfile.csv").write join([transpose(if(K13:K2000="","",A13:A2000&";"&K13:K2000))],vbcrlf)
end sub