如果将值放入CSV文件中(For i)

时间:2018-05-25 11:52:08

标签: vba excel-vba excel

我的代码无效,我似乎无法在已提问的问题中找到解决方案。

我想将数据粘贴到CSV文件中,但它似乎无法找到它。

它的错误

outputFile.Cells(i,2)= 1949.5 +(Worksheets(“Base”)。Cells(i,5)/ 2)

这是我找到数据的地方。有人能看出什么问题吗?

Sub works()

Dim outputFile          'Pointer to the file
Dim outputFileName      'Filename of the export file
Dim outputPath          'Path for the file

Dim numRows
Dim currentRow

Dim writeFile
Dim fileExists

writeFile = vbYes

outputFile = FreeFile
outputFileName = "AdminExport.csv"
outputPath = Application.ActiveWorkbook.Path

fileExists = Dir(outputPath & Application.PathSeparator & outputFileName)

If (fileExists <> "") Then
    writeFile = MsgBox("File already exists at the moment!" & vbCrLf & "Do you want to overwrite it with a new one?", vbYesNo + vbCritical)
End If

If (writeFile = vbYes) Then
    Open outputPath & Application.PathSeparator & outputFileName For Output Lock Write As #outputFile
    'Lock write = VBA har fuld rettighed til dokumentet (Ekslusivt)

    For i = 2 To 18288
        If Left(Worksheets("Base").Cells(i, 12), 6) = "262015" Then
        outputFile.Cells(i, 2) = 1949.5 + (Worksheets("Base").Cells(i, 5) / 2)
        End If
    Next i

    Print #outputFile, "Person_ID;STUDENT_ID_OLD;STUDENT_ID_NEW;ENROLL_PERIOD"
    'Overskrifter i CSV-filen

    numRows = Worksheets("Base").Range("A1").End(xlDown).Row
    For currentRow = 2 To numRows
    'Tæller antal rækker i "Base"

    Print #outputFile, Worksheets("Base").Range("A" & currentRow) & ";" & Worksheets("Base").Range("B" & currentRow)


    Next
End If

Close outputFile
'Lukker den, da vi har 'open' oppe over





End Sub

1 个答案:

答案 0 :(得分:0)

问题在于您获得错误的代码中的这部分代码:

outputFile.Cells(i, 2) 

在写入二进制文件时,不能像在Excel中那样引用单元格。您需要使用print语句。请参阅this教程。