将整数写入VBA窗口表单中的数组



在下面的代码中,我打开了一个.txt文件,我从这个文件中获取了itemNr。因为我想尽快用这个 itemNr 进行计算(仍然需要添加(,所以我想将这个 ItemNr 作为整数获取。在此之后,我想将 ItemNr 转换为字符串,以便我可以将其添加到我的数组中。由于某种原因,整数和字符串之间的转换没有发生,数组最后为空。

Private materiaal As String
Private dichtheid As String
Private vorm As String
Private afmetingen As String
Private itemNr As Integer
Private gegevens() As String

Private Sub BtnDo_Click(sender As Object, e As EventArgs) Handles btnDo.Click
Dim index As Integer = 0
'Dialoogbox openen dlgOpenen komt uit toolbox
Dim result As String
Dim itemNr As Integer
If dlgOpenen.ShowDialog = DialogResult.OK Then
'Controleer of er geen Cancel werd gekozen
Try
FileOpen(1, dlgOpenen.FileName, OpenMode.Input) 'bestand openen voor input
Do Until EOF(1)
Input(1, itemNr)
Input(1, materiaal)
Input(1, dichtheid)
Input(1, vorm)
Input(1, afmetingen)
'calucations will be done here in future 
result = CStr(itemNr)
gegevens(index) = result
index += 1
Loop

Catch ex As Exception
MsgBox("Fout bij openen, nr: " & Err.Number & " type: " & ex.GetType.ToString)
Finally
FileClose(1)
End Try
End If

Dim bestandsnaam As String
If dlgBewaren.ShowDialog = DialogResult.OK Then 'de gebruiker wil bewaren
bestandsnaam = dlgBewaren.FileName 'ingegeven bestandsnaam
Try
FileOpen(2, bestandsnaam, OpenMode.Output)
PrintLine(2, gegevens)
Catch ex As Exception
MsgBox("Fout bij schrijven, nr: " & Err.Number & " type: " & ex.GetType.ToString)
Finally
FileClose(1)
End Try
End If

End Sub

新旧代码的奇怪组合。 这是旧VB6程序的转换吗?

您不应该将 Try/Catch 模型与旧的 Err 对象混合使用,这两件事不应该放在一起。

而不是数组:

Private gegevens() As String

更改为列表(字符串(:

Private gegevens As New List(Of String)

然后,您只需向其添加内容,它就会自动增长。

通过使用 File.WriteAllLines((,可以大大简化写入新文件的过程。

请考虑迁移到较新的 StreamReader 模型来读取文件。 我保留了代码,因为我不记得有关遗留Input()函数如何工作的所有细节。

使用较新的 MessageBox.Show(( 代替 MsgBox。

下面是修改后的代码:

Private materiaal As String
Private dichtheid As String
Private vorm As String
Private afmetingen As String
Private itemNr As Integer
Private gegevens As New List(Of String)
Private Sub BtnDo_Click(sender As Object, e As EventArgs) Handles btnDo.Click
Dim index As Integer = 0
'Dialoogbox openen dlgOpenen komt uit toolbox
Dim result As String
Dim itemNr As Integer
If dlgOpenen.ShowDialog = DialogResult.OK Then
'Controleer of er geen Cancel werd gekozen
Try
FileOpen(1, dlgOpenen.FileName, OpenMode.Input) 'bestand openen voor input
Do Until EOF(1)
Input(1, itemNr)
Input(1, materiaal)
Input(1, dichtheid)
Input(1, vorm)
Input(1, afmetingen)
'calucations will be done here in future 
result = CStr(itemNr)
gegevens.Add(result)
Loop
Catch ex As Exception
MessageBox.Show("Fout bij openen: " & ex.ToString)
Finally
FileClose(1)
End Try
End If
Dim bestandsnaam As String
If dlgBewaren.ShowDialog = DialogResult.OK Then 'de gebruiker wil bewaren
bestandsnaam = dlgBewaren.FileName 'ingegeven bestandsnaam
Try
System.IO.File.WriteAllLines(bestandsnaam, gegevens)
Catch ex As Exception
MessageBox.Show("Fout bij schrijven: " & ex.ToString)
End Try
End If
End Sub

最新更新