简体   繁体   English

设置 Range.Value 时的 Excel VBA“溢出”错误

[英]Excel VBA “Overflow” Error on setting Range.Value

I have a macro that runs when the Excel workbook is opened, and basically takes data from a tab named "current day" and moves it to "previous day" and then takes data from another workbook and pastes it into current day(actually uses range.value not copy/paste).我有一个在 Excel 工作簿打开时运行的宏,基本上从名为“当天”的选项卡中获取数据并将其移动到“前一天”,然后从另一个工作簿中获取数据并将其粘贴到当天(实际上使用范围.value 不是复制/粘贴)。 Everything was working fine for multiple tests over several days.几天内的多次测试一切正常。 However, now it is throwing an Overflow Error on the Range.Value part of the code.但是,现在它在代码的 Range.Value 部分抛出一个溢出错误。 This is definitely not a size issue as the code is:这绝对不是大小问题,因为代码是:

PrevDay.Range("A1:Q" & ScoreCurRows).Value = CurrDay.Range("A1:Q" & ScoreCurRows).Value

Where ScoreCurRows is declared as a Long and pulls the UsedRange from the "Current Day" sheet and PrevDay is defined as Sheets("Previous Day") and CurrDay is defined as Sheets("Current Day").其中 ScoreCurRows 被声明为 Long 并从“Current Day”表中提取 UsedRange,PrevDay 被定义为 Sheets(“Previous Day”),CurrDay 被定义为 Sheets(“Current Day”)。 It also is usually under 20 rows worth of data, so even if it was an integer, this still shouldn't cause a problem.它通常也少于 20 行的数据,所以即使它是一个整数,这也不应该引起问题。

Does anyone have an idea why this is suddenly throwing an Overflow Error and if there is something I should be looking for?有谁知道为什么这会突然引发溢出错误,以及是否有我应该寻找的东西?

You must have some values in the source range that caused the overflow when VBA tried to load them into a variant array in当 VBA 尝试将它们加载到变量数组中时,源范围中必须有一些值导致溢出

= CurrDay.Range("A1:Q" & ScoreCurRows).Value

For example, a cell formatted as date with a value that's too large for a date.例如,格式为日期的单元格的值对于日期而言太大。 For this reason, use .Value2 instead, which will return the dates as normal numbers without trying to convert them.Besides, although most posts on SO donmt stick to this rule, it is known good practice to always use .Value2 when reading a range value (not necessarily when assigning).出于这个原因,使用.Value2代替,它会将日期作为正常数字返回而不尝试转换它们。此外,尽管 SO 上的大多数帖子都没有遵守此规则,但在读取范围时始终使用.Value2是众所周知的好习惯值(不一定在分配时)。

PrevDay.Range("A1:Q" & ScoreCurRows).Value = CurrDay.Range("A1:Q" & ScoreCurRows).Value2
'                                                                                 ^^^^^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM