我试图从一个 CSV 文件中填充数组,该文件在单词之间有空格,而在我用连字符替换所有空格后,我试图填充的第二个文件。
因此,array1 的内容看起来像这样“Hi there”,而 array2 的内容看起来像这样“Hi-there”。
我试过使用 replace(text, old, new) 但我遇到了问题。在没有其他潜艇的独立宏中,它可以工作。如果有任何其他潜艇没有,抛出错误说“错误数量的参数或无效的属性分配”
这是我得到的代码:
Private Sub import_csv()
Dim file_name As String
Dim fnum As Integer
Dim whole_file As String
Dim lines As Variant
Dim one_line As Variant
Dim num_rows As Long
Dim num_cols As Long
Dim the_array() As String
Dim imported_array() As String
Dim txt As String
Dim R As Long
Dim C As Long
file_name = "test.csv"
'load the file
fnum = FreeFile
Open file_name For Input As fnum
whole_file = Input$(LOF(fnum), #fnum)
Close fnum
'Break the file into lines
lines = Split(whole_file, vbCrLf)
'Dimension the array
num_rows = UBound(lines)
one_line = Split(lines(0), ",")
num_cols = UBound(one_line)
ReDim the_array(num_rows, num_cols)
ReDim imported_array(num_rows, num_cols)
'Copy the data into the arrays
For R = 0 To num_rows
If Len(lines(R)) > 0 Then
one_line = Split(lines(R), ",")
For C = 0 To num_cols
imported_array(R, C) = one_line(C)
txt = one_line(C)
txt = replace(txt, " ", "-") '<----- problem line
the_array(R, C) = txt
Next C
End If
Next R
End Sub