0

这是一个奇怪的具体问题。假设我有一个产生值为 0 的单元格。我正在将其写入文本文件。

当我写它而不是 0 时,我希望有四个空格(它本质上是 null 的视觉占位符)。

这条线的问题:

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

- - - - - - - - - - - - - - - - -更新 - - - - - - - - ----------------------

所以我们只是决定在 isBLANK 条件下做一个 excel 表,如果它是假的,则显示 4 个空格。现在应该可以了。感谢所有的帮助。它本质上是一组空白单元格,并被转移到一张新表上。因此,由于某种原因,它总是显示 0 以显示其空白。我们决定 if else 是最好的。

Excel 代码:

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

2 回答 2

2

您的代码有几个问题:-

  1. 您已无缘无故地定义cellValue为 a 。Variant最好使用最能代表数据的数据类型来声明变量。您可以简单地将其声明为 a 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...
于 2015-06-15T19:15:13.150 回答
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
于 2015-06-15T19:20:15.800 回答