2015-06-15 120 views
0

這是一個奇怪的具體問題。假設我有一個產生值爲0的單元格,我將它寫入一個文本文件。(VBA EXCEL)用四個空格替換0 0

當我寫它而不是0我希望有四個空格(它本質上是一個空的可視佔位符)。

問題這一行:

cellValue = Replace(cellValue, 0, " ") 

這往往與四個空格來代替全零。有人知道如何解決這個問題嗎?我將不勝感激任何幫助。

樣品輸入:

0 | 100 | 48 

樣本輸出:

____10048 (Underscores are spaces). 

我到目前爲止有:

Dim myFile As String, rng As Range, cellValue As Variant, I As Integer, j As Integer 

myFile = Application.DefaultFilePath & "\test_data_output.txt" 
Set rng = Selection 
Open myFile For Output As #1          

For I = 1 To rng.Rows.Count 
    For j = 1 To rng.Columns.Count 
cellValue = Replace(cellValue, 0, " ") 
cellValue = cellValue + CStr(rng.Cells(I, j).Value) 
If j = rng.Columns.Count Then 
    Print #1, cellValue 
End If 

    Next j 
    cellValue = "" 
Next I 

Close #1 

------------- -------------------- UPDATE ----------------------------- ---------

所以我們只是決定做一個Excel表,如果isBLANK條件顯示4個空格,如果它是假的。這應該現在工作。感謝所有的幫助。它實質上是一組空白的細胞,被轉移到一張新紙上。因此,出於某種原因,它總是顯示0表明其空白。我們決定如果否則會是最好的。

的Excel代碼:

=IF(ISBLANK('OurSheetName'!I7)," ",'OurSheetName'!I8) 
+0

查找和替換('0 '與'')匹配整個單元格內容似乎值得嘗試。 – pnuts

+0

匹配整個單元格內容?這是一個命令嗎? – Dasman

+2

0 | 100 | 48 - 這正是你的牢房裏的數據嗎? – coder231

回答

2

一對夫婦與您的代碼的問題: -

  1. 您已經定義cellValueVariant沒有明顯的原因。您最好使用最能代表數據的數據類型來聲明變量。您可以簡單地聲明它爲String,除非您有充分的理由將其保留爲昂貴的Variant
  2. 我看不到你在哪裏給cellValue賦值。這是完整的代碼還是你編輯它發佈?如果沒有正確的評論來解釋被刪除的內容,就很難評估代碼是否被黑客發佈。

寫它之前,你可以簡單地測試值: -

... 

'Inside the "For j" loop 

cellValue = rng.Value 

'Test the value - but test it as a string value 
If cellValue = "0" Then 
    cellValue = " "  'Replace with 4 spaces 
End If 

'Carry on with code... 
+0

哦,你對我完全忘記包括這一行:cellValue = cellValue + CStr(rng.Cells(I,j)。值)出於某種原因如果cellValue Statement =不起作用。 – Dasman

1

在作出更換,只檢查如果單元格值爲0

For I = 1 To rng.Rows.Count 
    For j = 1 To rng.Columns.Count 
    If cellValue = 0 Then 
     cellValue = Replace(cellValue, 0, " ") 
    End If 
    If j = rng.Columns.Count Then 
     Print #1, cellValue 
    End If 
    Next j 
    cellValue = "" 
Next I