2016-12-05 77 views
-1

我想從CSV文件中填充單詞之間有空格的數組,以及在我用連字符替換所有空格後嘗試填充的第二個單詞。單詞vba文本替換數組

因此,array1的內容看起來像這樣「你好」,而array2的內容看起來像這樣「你好」。

我試過使用替換(文本,舊的,新的),但我遇到了問題。在沒有其他潛艇的獨立宏中,它是有效的。如果有任何其他的潛艇沒有,嘔吐和錯誤說

「的參數或無效的屬性賦值打錯了」這是我所得到的代碼:

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 
+0

您是否定義了名爲「replace」的函數?在VBA中已經有了一個這樣的名字的方法...... –

+0

我想我找出了問題所在。我嘗試使用VBA.Replace,它的工作。所以我通過引用,但找不到任何丟失:/ –

回答

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 
+0

我試圖創建一個自動查找和替換宏使用逗號分隔文件來保存搜索條件。這個計劃一旦被讀入數組,就讓宏對每個搜索詞進行迭代,以便用戶不必進行手動查找和替換。 –