我使用以下代码,该代码基于其他人在SO上的帖子。它打开另一个工作簿,复制工作表并将其粘贴回主工作簿。它"粘贴"这些值带有resize功能,因此pastespecial不可用。问题是源表的S列中有20个数字(跟踪号)的值,当它们被粘贴回主工作簿时,它们被截断为科学记数法并丢失。
Set SourceFile = Workbooks.Open("C:\users\user\desktop\shipping\tempshipping.xls")
Set DestFile = ThisWorkbook
With SourceFile.Sheets("Sheet1").UsedRange
'I tried using this to set the format of the cells in the source workbook
'to "Text" to fix the problem but I stepped through the code and actually
'checked the file when it's open and it's not doing anything
LastRow = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Range("S2:" & "S" & LastRow).NumberFormat = Text
'you can see here the "paste" method is taking the range value and resizing
'it to the source data, so pastespecial isn't available. I'm not even sure
'doing pastespecial would fix the problem.
'Now, paste to y worksheet:
DestFile.Sheets("DestSheet").Range("A1").Resize( _
.Rows.Count, .Columns.Count) = .Value
End With
'Close TEMP File
SourceFile.Close
答案 0 :(得分:3)
文字的Range.NumberFormat property为 @ ,而不是文字。
Dim lastRow As Long, cpyrng As Range
Dim SourceFile As Workbook, DestFile As Workbook
Set SourceFile = Workbooks.Open("C:\users\user\desktop\shipping\tempshipping.xls")
Set DestFile = ThisWorkbook
With SourceFile.Sheets("Sheet1").UsedRange
lastRow = .Cells.Find(What:="*", After:=.Cells(1), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Set cpyrng = .Range("S2:S" & lastRow)
cpyrng.NumberFormat = "@" '<~~ Use @; Not Text
End With
'transfer values to destination worksheet
With DestFile.Sheets("MobStub").Range("A1").Resize(cpyrng.Rows.Count, cpyrng.Columns.Count)
.NumberFormat = "@" '<~~ set the receiving number format first
.Value = cpyrng.Value
End With
'Close TEMP File
SourceFile.Close
您在With ... End With statement内遗漏了一些.
个引用。 .
中的.Cells
显示了With ... End With。