麻烦autoformatting存储为string的数字

我build立了一个例程,复制和粘贴数据,并在导入到我的书籍后,对上述数据进行各种分析。 分析部分工作正常,但数据似乎是作为string存储在各种excel书籍,当他们实际上是整数和longs。 Excel认识到这一点,并注释每个单元格用小绿色勾号标记,并提供给我格式化为数字,因为它们存储为string或我想“文本”。 这大大减慢了工作簿,因为这个信息大约有10个标签,他们都有相同的问题。

问题的另一个部分是数据中有合法的string不是数字,因此将整个表格格式化为数字将不起作用。

例如:从第5,6行中导入数据的工作表可能包含string,而列A和列C中的所有string到J的格式都将设置为string或文本格式。 然后,可能会有几行的rest,模式将重新开始。

提前致谢!

下面的代码仅仅是访问和复制数据,因为其余的分析是在一个相当大的函数中进行的:

Function GetOiData(productID As String, targetSheet As Worksheet, controlPanel As Worksheet) 'Function access OI data from the CME website and copies it into the book for all products Dim filePath As String Dim reportDate As String reportDate = controlPanel.Cells(1, 5) filePath = "http://www.cmegroup.com/CmeWS/exp/voiProductDetailsViewExport.ctl?media=xls&tradeDate=" & reportDate & "&reportType=P&productId=" & productID Workbooks.Open Filename:=filePath Cells.Select Selection.Copy targetSheet.Activate With targetSheet .Cells(1, 1).Select .Paste .Cells(1, 1).Select End With 'Clears clipboard and closes CSV file to avoid potential contamination Application.CutCopyMode = False Windows("voiProductDetailsViewExport").Activate Application.DisplayAlerts = False Workbooks("voiProductDetailsViewExport").Close Application.DisplayAlerts = True End Function 

第一个问题: …但是数据看起来像是string一样在线存储在各种excel书籍中,而实际上却是长整数。

假定不存在前导空格或尾随空格或不存在空格,请运行此快速例程以遍历工作簿并将文本类似的数字转换为真实数字。

 Sub fixTextThatLookLikeNumbers() Dim w As Long, c As Long With ActiveWorkbook For w = 1 To .Worksheets.Count With .Worksheets(w) For c = 1 To .UsedRange.Columns.Count With .Columns(c) If CBool(Application.CountA(.Cells)) Then _ .TextToColumns Destination:=.Cells(1), _ DataType:=xlFixedWidth, FieldInfo:=Array(0, 1) End With Next c End With Next w End With End Sub 

这将工作在列格式化为常规,但不是专门格式为文本的列。

第二个问题:问题的另一个部分是数据中有合法的string,不是数字,因此将整个表格设置为数字将不起作用。

如果您目前正在进行混合和匹配格式化,那么可以修改该代码以在所有列上强制使用常规格式。

这里是对函数代码的快速重写,它应该使用原始值的直接转换,而不是复制和粘贴(或粘贴特殊)操作。

 Function GetOiData(productID As String, targetSheet As Worksheet, controlPanel As Worksheet) 'Function access OI data from the CME website and copies it into the book for all products Dim filePath As String, reportDate As String, data As Range reportDate = controlPanel.Cells(1, 5).Value filePath = "http://www.cmegroup.com/CmeWS/exp/voiProductDetailsViewExport.ctl?media=xls&tradeDate=" & reportDate & "&reportType=P&productId=" & productID With Workbooks.Open(Filename:=filePath, ReadOnly:=True) With .Worksheets(1).Cells(1, 1).CurrentRegion targetSheet.Cells(1, 1).Resize(.Rows.Count, .Columns.Count) = .Value2 End With 'closes CSV file to avoid potential contamination Application.DisplayAlerts = False .Close SaveChanges:=False End With 'this always turns back on when you exit the function 'Application.DisplayAlerts = True End Function