简体   繁体   中英

Getting questionmark characters (?) when reading file line by line into worksheet

替代文字

I am reading a text file line by line with VBA into a worksheet. it's often returning these characters. Does anyone know how to remove them?

this is how i am reading it:

Sub ReadAsciiFile()

    Dim sFileName As String
    Dim iFileNum As Integer
    Dim sBuf As String
    Dim i As Integer
    i = 1

    ' edit this:
    sFileName = "usmap.txt"

    ' does the file exist?  simpleminded test:
    If Len(Dir$(sFileName)) = 0 Then
        Exit Sub
    End If

    iFileNum = FreeFile()
    Open sFileName For Input As iFileNum

    Do While Not EOF(iFileNum)
        Line Input #iFileNum, sBuf
        ' now you have the next line of the file in sBuf
        ' do something useful:
        activesheet.Cells(i, 1) = sBuf
        i = i + 1
        Debug.Print sBuf
    Loop

    ' close the file
    Close iFileNum

End Sub

First, if you're copying and pasting into Excel, check your paste method and try "Paste Special" as Text (as opposed to HTML or Unicode Text).

You can also use a simple VBA function to find out what the invalid characters are. Then you could either use another VBA function to remove the invalid characters or use the Excel formula Substitute() function which I showed in the last question you asked. Here's a quick example of some VBA code to see what characters exist in cell A1 :

Sub PrintChars()
  Dim intLen As Integer
  Dim str As String
  str = Range("A1").Value
  intLen = Len(str)
  Dim intCount As Integer
  intCount = 1

  Dim strChar As String

  Do While intCount <= intLen
    strChar = Mid(str, intCount, 1)
    Debug.Print strChar & ": " & Asc(strChar)
    intCount = intCount + 1
  Loop

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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