vba - 哪个更快,变量或直接访问单元格值?

标签 vba excel

好吧,我有很多字符串操作,例如

1st one
ActiveSheet.Cells(i, "B").Value = Replace(ActiveSheet.Cells(i, "B").Value, ",", " ")
ActiveSheet.Cells(i, "B").Value = Replace(ActiveSheet.Cells(i, "B").Value, "/", " ")
ActiveSheet.Cells(i, "B").Value = Replace(ActiveSheet.Cells(i, "B").Value, "&", " ")
ActiveSheet.Cells(i, "B").Value = Replace(ActiveSheet.Cells(i, "B").Value, "(", " ")
2nd one
store=ActiveSheet.Cells(i, "B").Value
store= Replace(store, "/", " ")
store = Replace(store, "&", " ")
store = Replace(store, "(", " ")

和一些修剪操作,有时会找到字符串长度,有时还会进行比较。

我必须对单元格 1 到 4000 进行循环。问题是将单元格值存储在字符串中并且访问更好更快?或者在宏中写入activesheet单元格值本身更快?
store = activesheet.cells(i,"B").value and use store everywhere 
or write activesheet.cells(i,"B").value everywhere?

哪个更好哪个更优化我有点想如果我们提到它必须去工作表并将其取回的单元格值但是如果我们将它存储在变量中那么它可能会更快。我只需要知道哪个更好?

最佳答案

访问 Excel 很慢。将您将访问两次以上的内容存储在一个变量中总是会更快,并且将一系列单元格(对 Excel 的一次调用)转储到一个变量数组中会更好。

请记住,Excel 和 VBA 并不相同。这就像两个人在同一个公寓但不同的房间。每次访问 Excel 时,VBA 都必须敲开 Excel 的大门。

更新 :
以上是对所有代码的一般建议。关于上面的特定代码以及您正在做什么,实际上使用 Excel 的搜索和替换功能可能会更快,如下所示:

Sub test()

Application.ScreenUpdating = False
With Range("B1:B4000")
    .Replace what:="(", replacement:=" ", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

    .Replace what:="&", replacement:=" ", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

    .Replace what:="/", replacement:=" ", LookAt:=xlPart, SearchOrder _
    :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
End With
Application.ScreenUpdating = True
End Sub

关于vba - 哪个更快,变量或直接访问单元格值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7416182/

相关文章:

excel - 使用 PowerShell 中的参数启动 Excel 宏

c# - 从多个线程访问 word 文档的单词列表

excel - 当重要的输入文本框为空时如何生成错误

python - 使用 openpyxl 写入一列

vba - Excel VBA 在单元格中打印即时窗口的结果

vba - 如何将所有列中的内容从 Excel 中获取到文本文件中?

vba - 将文本框控件传递给专用子功能

xml - 如何更改 Excel 的默认 XML 输出编码?

vba - 在 VBA 中通过字符串的值调用变量

excel - 检测格式化为文本的重复项