-3

I have this code

Dim FileToOpen As Variant
Dim OpenBook As Workbook

FileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")

If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).UsedRange.Select
Selection.NumberFormat = "@"
OpenBook.Sheets(1).UsedRange.Copy
ThisWorkbook.Worksheets("BOM").Range("C1").PasteSpecial xlPasteValues
OpenBook.Close False
End If

Which is how I tried to automate manual actions of:

  1. Opening a .txt file
  2. Ctrl + a
  3. Ctrl + c
  4. Pasting it in my workbook via VBA code which is irrelevant in this case.

In the end I end up with this kind of table (main workbook in the image below has .NumberFormat = "@"): https://i.stack.imgur.com/98tiC.png

But when I run it with the code above - I end up with:

https://i.stack.imgur.com/bJahk.png

Ignore the column titles in the row 1.

The problem I faced is that this code I have above, opens .txt file contents with already lost leading "0" in a temporary excel workbook from where it then copies them to my active workbook.

I'm wondering if there's any ways around it to get what I am looking to get done i.e. properly automating the sequence of manual actions listed above via VBA code displaying a search message box as it does now and then me choosing a .txt file I need and getting all the contents from it to my active workbook while maintaining all leading zeros (the number of zeroes and length of strings may vary so no solutions of adding them back in again won't be what I'm looking for)

Eduards
  • 68
  • 2
  • 20
  • So to clarify, the issue is that you want to paste a string - that can be parsed as a number - as a string and not have it automatically convert to a number on paste?, e.g. 00100 paste as 00100 not 100? can u give a screenshot of the input file? – JohnnieL Feb 23 '21 at 14:49
  • I guess so. I have values like 005 and when my code opens such in that temporary workbook - the leading zeros disappear leaving only 5 which I seem to not be able to recover afterwards. So the issue is in the method how I try to get contents of .txt file to excel workbook or in my code there's something missing :) When I copy all the contents as described in the post, I use .NumberFormat = "@" in my main workbook to maintain the leading zeros. But now that I try to automate the manual copying I lose all leading zeros despite the fact that my destination workbook is formated correctly – Eduards Feb 23 '21 at 14:54
  • can u give an example of the text file you are trying to read please – JohnnieL Feb 23 '21 at 14:56
  • Thats not helpful - can you post a screen shot of the file in a text editor or a link to an example and be clear about what your column delimiters are thanks – JohnnieL Feb 23 '21 at 15:01
  • 1
    Does this answer your question? [How to paste text with leading "0" in excel](https://stackoverflow.com/questions/66331847/how-to-paste-text-with-leading-0-in-excel) – Nathan_Sav Feb 23 '21 at 15:12
  • 1
    Is this a dupe of https://stackoverflow.com/questions/66331847/how-to-paste-text-with-leading-0-in-excel?noredirect=1#comment117269643_66331847? – Nathan_Sav Feb 23 '21 at 15:13
  • Ok, last time I try: "Thats not helpful - can you post a screen shot of the file in a text editor or a link to an example and be clear about what your column delimiters are thanks" showing the file already in excel is not what was asked for. thanks – JohnnieL Feb 23 '21 at 15:21
  • I genuinely don't see a difference between text editor and excel screenshots, but whatever... Here's a TXT file example: https://easyupload.io/9a6hsh In text import wizard if pasted manually the settings are as follows: Delimiters: Tab (nothing else checked) Column data format: Text on all the columns – Eduards Feb 23 '21 at 15:26

1 Answers1

1

The issue that you have is that as soon as excel gets hold of the data it creates problems.

So read it as a text file and split each line and output that directly to your target range - it will therefor stop excel parsing any strings as values - after that you can do whatever you want

option explicit
Sub read_text()

  Dim FileToOpen As Variant
  FileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
  
  Dim max_cols As Long
  max_cols = 0
  
  Dim r_out As Range
  Set r_out = ThisWorkbook.Worksheets("BOM").Range("C1")
  Dim row_offset As Long
  
  
  offset = 0
  If FileToOpen <> False Then
    Dim fso As Object
    Dim file As Object
  
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set file = fso.OpenTextFile(FileToOpen, 1)
    
    While Not file.AtEndOfStream
      Dim line As String
      line = file.ReadLine
      
      Dim line_arr As Variant
      line_arr = Split(line, vbTab)
      ThisWorkbook.Worksheets("BOM").Range("C1").offset(row_offset, 0) _
             .Resize(1, UBound(line_arr) - LBound(line_arr) + 1).Value = line_arr
      row_offset = row_offset + 1
    Wend
  
    file.Close
  End If

End Sub

output

enter image description here

JohnnieL
  • 1,192
  • 1
  • 9
  • 15
  • Thank you! That works wonders! However it some why pastes it one row too low (In C2 as upper right rather than C1 as upper right). Would be infinitely thankful if you'd edit that little imprecision in your answer to comply with the original issue :) – Eduards Feb 23 '21 at 15:54
  • amended - `row_offset = row_offset + 1` should be the last statement in the while loop – JohnnieL Feb 23 '21 at 15:55
  • Do you want to ignore the first row of headers? – JohnnieL Feb 23 '21 at 15:57
  • I don't understand your question, the code now pastes the TXT file starting from C2 but it should be C1. That's all :) – Eduards Feb 23 '21 at 15:58
  • Two separate statements (1) "amended - row_offset = row_offset + 1 should be the last statement in the while loop" this will paste into c1 not c2 (2) Do you want to ignore the first row of headers? – JohnnieL Feb 23 '21 at 16:00
  • Simpler to understand solution is to set offset = 0 To offset = -1 And that fixes it even tho leaving probably unnecessary offset functions. P.S. No I don't want to ignore nothing. Thank you for your assistance! – Eduards Feb 23 '21 at 16:56
  • Glad it helped no problem – JohnnieL Feb 23 '21 at 16:57