-1

我试图从一个 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
4

1 回答 1

0

对不起,但这对我来说听起来很奇怪。您正在尝试使用 Word 在 CSV 文件中进行查找/替换?是这样吗?你为什么还要这样做?这是 Word 文档中的典型查找/替换。

Sub FindAndReplaceFirstStoryOfEachType()
  Dim rngStory As Range
  For Each rngStory In ActiveDocument.StoryRanges
    With rngStory.Find
      .Text = "find text"
      .Replacement.Text = "I'm found"
      .Wrap = wdFindContinue
      .Execute Replace:=wdReplaceAll
    End With
  Next rngStory
End Sub 

这是更新 Word 文档正文中的内容。现在,如果您想在数据文件中进行查找/替换,无论是 CSV、TXT 还是 Excel 文件,您都应该使用 Excel 来完成此类任务。

Sub Update_CSV()
    Open "C:\test.csv" For Input As #1
    c0 = Input(LOF(1), #1)
    Close #1

    Open "C:\test.csv" For Output As #1
    Print #1, Replace(c0, "OLD TEXT", "NEW TEXT")
    Close #1
End Sub
于 2016-12-06T00:00:15.037 回答