我的Excel VBA需要大约300个XLS文件,并抓取8个单元格存入自己的行。 (Office11)我有几个子函数和函数,它们使用位置常量作为sourceData和destination位置。总计我有23个恒定位置,列号,单元格位置。
问题:有关如何清理可读性并将常量保存在一个位置的任何建议吗?我试图避免公共变量但不确定更好的方法。你如何做包含常数值的数组?
部分示例,
Public pstrQLocations(1 To 8) As String
pstrQLocations(1) = "B7"
pstrQLocations(2) = "B6"
pstrQLocations(3) = "B5"
pstrQLocations(4) = "B8"
pstrQLocations(5) = "A3"
pstrQLocations(6) = "C8"
答案 0 :(得分:1)
您可以将常量存储在Collection
中。优点是,您可以为您的元素命名。
Option Explicit
Dim pstrQLocations As Collection
Private Sub initializeConstants()
Set pstrQLocations = New Collection
pstrQLocations.Add "B7", "Title"
pstrQLocations.Add "B6", "User"
End Sub
Private Sub showConstants()
initializeConstants
Debug.Print Me.Range(pstrQLocations("Title")).Value
Debug.Print Me.Range(pstrQLocations("User")).Value
End Sub
3D版本:
Option Explicit
Dim pstrQLocations As Collection
Private Sub initializeConstants()
Dim title As New Collection
Set pstrQLocations = New Collection
title.Add "B7", "source"
title.Add "A6", "destination"
pstrQLocations.Add title, "Title"
End Sub
Private Sub showConstants()
Dim y As Collection
initializeConstants
Debug.Print pstrQLocations("Title")("source")
Debug.Print pstrQLocations("Title")("destination")
End Sub