简体   繁体   English

Excel to Text VBA之前带有问号-如何解决?

[英]Excel to Text VBA precedes with question mark - how to fix?

I'm very new to VBA in Excel. 我对Excel中的VBA非常陌生。 I'm using this code I cobbled together from example snippets online to convert a column of cells in Excel to a text file: 我正在使用从示例网上摘录的这段代码将Excel中的单元格列转换为文本文件:

Private Sub CommandButton1_Click()
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
Dim FName As String
Dim FPath As String

Set fsT = CreateObject("ADODB.Stream"): 'Create Stream object
fsT.Type = 2: 'Specify stream type – we want To save text/string data.
fsT.Charset = "utf-8": 'Specify charset For the source text data.

FPath = "C:\WHIT\ParamGen"
FName = Sheets("Sheet1").Range("b49").Text

myFile = FPath & "\" & FName

Set rng = Range("B2: B42 ")

Open myFile For Output As #1

For i = 1 To rng.Rows.Count
    For j = 1 To rng.Columns.Count

cellValue = rng.Cells(i, j).Value

If j = rng.Columns.Count Then
    Print #1, cellValue
Else
    Print #1, cellValue,
End If

    Next j
Next i

Close #1

End Sub

The problem is that the first cell in my Excel file contains this text: 问题是我的Excel文件中的第一个单元格包含以下文本:

@!=1 @!= 1

...and it shows up in the generated text file like this: ...它显示在生成的文本文件中,如下所示:

?@!=1 ?@!= 1

Everything else in the excel file gets written to the text file without issue, but that question mark messes up the import function in the software this file is being generated for. excel文件中的所有其他内容都将毫无问题地写入文本文件,但是问号弄乱了为此文件生成的软件中的导入功能。

Any ideas on getting this question mark to disappear? 关于使这个问号消失的任何想法?

Have you tried removing the "?" 您是否尝试删除了“?” with code in the file, such as: 文件中的代码,例如:

If left(cellvalue,1)="?" then 
    application.substitute(cellvalue,"?","") 
end if

I ran this code with the first cell containing @!=1 and it wrote correctly to the text file as @!=1 (no ? added). 我在第一个包含@!= 1的单元格中运行了此代码,并将其正确地以@!= 1的形式写入了文本文件(未添加?)。 Did you check to see if cell B2 contains any non-printable characters? 您是否检查了单元格B2是否包含任何不可打印的字符?

I found a solution. 我找到了解决方案。 Excel was treating the @!=1 in the first cell as a function, but it wasn't a functional function. Excel将第一个单元格中的@!= 1视为函数,但它不是函数。 My best guess is that it was throwing an invisible character in there as it parsed it into a text file. 我最好的猜测是,在将其解析为文本文件时,它在其中抛出了一个不可见的字符。 Overwriting the offending cell with '@!=1 did the trick. '@!= 1覆盖有问题的单元格可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM