使用Application.GetOpenFilename后closuresvba中的文件

我正在使用名为OpenSees的软件对钢筋混凝土build筑进行分析。 分析的结果写在txt文件中,所以为了分析这些结果,我使用vba读取和写入txt文件到Excel中。 第一次写入数据没有问题。

第一次将txt文件写入Excel之后,我的问题就出现了,我尝试在不closuresExcel的情况下第二次运行OpenSees。 Opensees指出,txt文件是打开的,所以它不能覆盖它们。 我使用closures#1后应该closures文件。

到目前为止我所做的是第一次运行OpenSees,使用vba在Excel中写入结果,保存并closuresExcel,第二次运行OpenSees,等等。

我用来写文件的主要代码是

ruta1 = Application.GetOpenFilename("text Files (*.out),*.out", MultiSelect:=True) If Not IsEmpty(ruta1) Then For i = LBound(ruta1) To UBound(ruta1) Open ruta1(i) For Input As #1 Do Until EOF(1) Line Input #1, linea valor = Split(linea, " ") ' valor(i) : 0 time - 1 Ux - 2 Uy - 3 Rz h5.Cells(f_elong + j, c_elong) = valor(1) / hw * 100 h5.Cells(f_elong + j, c_elong + 1) = valor(2) / lw * 100 h6.Cells(f_FD + j, c_FD) = valor(1) / hw * 100 j = j + 1 Loop Close #1 Next End If 

不知道这是否会解决您的问题,但不要硬编码文件编号; 使用FreeFile函数,让VBA给你一个文件编号:

 Dim fileNumber As Integer fileNumber = FreeFile Open ruta1(i) For Input As #fileNumber Do Until EOF(fileNumber) Line Input #fileNumber, linea ... Loop Close #fileNumber 

此外,你正在处理外部资源 – 这里应该有适当的error handling,清理子程序,确保所有打开的文件在程序退出前closures:

  On Error GoTo CleanFail Dim fileNumber As Integer ... CleanExit: Close 'hammer: no file number closes all opened files Exit Sub CleanFail: MsgBox Err.Description, vbCritical Resume CleanExit End Sub 

我不认为只使用#1作为文件处理程序是有问题的,因为在处理完成后Close它。 我无法真正模拟为什么你在代码中遇到问题,但是可以在下面尝试testing它是否适用于您。 不是你的问题的直接答案,只是一个可能的解决方法。

 Dim ruta1 As Variant ruta1 = Application.GetOpenFilename("text Files (*.out),*.out", MultiSelect:=True) If IsArray(ruta1) Then Dim linea, lines ' implicit Variant declaration For i = LBound(myTxt) To filecount Open myTxt(i) For Input As #1 ' Open the file ' Retrieve the lines of text and dump in an array lines = Split(Input$(LOF(1), #1), vbNewLine) Close #1 ' Close the file ' Work with the array instead of reading each line of the opened file Dim j As Long: j = 1 ' Or depending on what start value you require For Each linea In lines valor = Split(linea, " ") ' valor(i) : 0 time - 1 Ux - 2 Uy - 3 Rz h5.Cells(f_elong + j, c_elong) = valor(1) / hw * 100 h5.Cells(f_elong + j, c_elong + 1) = valor(2) / lw * 100 h6.Cells(f_FD + j, c_FD) = valor(1) / hw * 100 j = j + 1 Next Next End If