How to make sure all excel cells formatted as text in a column actually are

亡梦爱人 提交于 2019-12-07 21:55:02

问题


I have a column of content submitted by multiple users, generally pasted into a sheet, from multiple sources. This column has numbers that should always be formatted as text. In fact, no matter how this is done, there are always a few items that never have the indicator in the left corner warning that these are formatted as text (which we want to see in all cases)

Checking the individual cell, it does show as formatted text, but in reality on an import into a datatable, if the indicator is missing, the datatype is imported as a number. Clicking after the number and hitting Enter will change the indicator to text.

How can I do that in VBA? I don't want to visit each cell, click on the end of the content and hit enter.Cutting and paste special in no combination reliably fixes these.

What does excel look at, which gets the format issue right with these text format warning indicators, and yet doesn't seem to get it right when you look at the cell format properties?

Excel 2003 but have had the same issue in later versions too.


回答1:


What worked for me was to check the error indicator, which seemed more reliable than the cell format itself. This looks for anything missing the indicator and forces it to be text.

Unless someone knows something further concerning why this should NOT be done, it solves my issue.

Sub check4textformat()
 For Each cell In Range("E2:E15000")
 If cell.Errors.Item(xlNumberAsText).Value = False Then cell.Formula = cell.Text
 Next
End Sub



回答2:


Since your main target is not visiting each cell, I will suggest an easier way than VBA (actually, it's probably the easiest way).

  1. Select the desired column.
  2. Go to Data > Text to Columns.
  3. Select "Delimited" (should be already selected by default) and press "Next".
  4. Uncheck all delimiters and press "Next" (you can also leave the default state of "Tab" as the only delimiter).
  5. Under "Column Data Format", select "Text" and click "Finish".

Done. All the numbers in the column should be stored as text now.




回答3:


You really only need to prepend the text indicator character "'" before every number. Assuming that your values are in the first column, in the first 120 rows, you can do it like this:

For i = 1 To 120
    Me.Cells(i, 1).Value = "'" & Me.Cells(i, 1).Value
Next i

If the cell already has a text value, the prepending is ignored. When copying (and when obtaining the value in VBA) the "'" is completely ignored as it only indicates the "type" of the cell contents.



来源:https://stackoverflow.com/questions/9007404/how-to-make-sure-all-excel-cells-formatted-as-text-in-a-column-actually-are

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!