问题
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).
- Select the desired column.
- Go to Data > Text to Columns.
- Select "Delimited" (should be already selected by default) and press "Next".
- Uncheck all delimiters and press "Next" (you can also leave the default state of "Tab" as the only delimiter).
- 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