我在設計這個我正在製作的小報告時遇到了麻煩。是否可以在Excel VBA中爲Range對象創建一個變量,用於將格式應用於另一個Range?這是我的例子:作爲對象存儲範圍屬性?
我創建從Microsoft腳本運行時庫的字典:
Dim d as Scripting.Dictionary
有了這個我添加標籤,值和(嘗試添加)的範圍。
Dim rng as Range
rng.Font.Bold = True
d.Add 1, Field("test1", 12345, rng)
rng.Font.Bold = False
d.Add 2, Field("TestTwo", "Testing field", rng)
rng.HorizontalAlignment = xlCenter
d.Add 3, Field("threeeee", 128937912, rng)
Dim key As Variant
For Each key In d.keys
Range("A" & key).value = d(key).Label
Set Range("B" & key).value = d(key).rng
Next key
這裏是我的現場功能:
Private Function Field(Label As String, val As Variant, rng As Range) As cField
Dim f As New cField
f.Label = Label
f.val = val
Set f.rng = rng
Set Field = f
End Function
這裏是我的cField類:
Option Explicit
Dim mVarValue As Variant
Dim mStrLabel As String
Dim mRng As Range
Property Let val(ByVal val As Variant)
mVarValue = val
End Property
Property Get val() As Variant
val = mVarValue
End Property
Property Let Label(ByVal val As String)
mStrLabel = val
End Property
Property Get Label() As String
Label = mStrLabel
End Property
Property Let rng(ByVal val As Range)
Set mRng = val
End Property
Property Get rng() As Range
Dim a As Range
a.value = mVarValue
Set rng = a
End Property
的想法是,在字典中的關鍵將是該行的位置爲領域。這樣,如果需要對我製作的報告進行更改,唯一需要更改的是字典中特定值的關鍵字。我已經成功地存儲了標籤的價值和價值本身,但我也想存儲該範圍的格式(粗體,理由,邊框等...)。
我得到一個'運行時錯誤'91':對象變量或塊變量未設置'錯誤緊接在rng聲明之後的行上。我想知道如果它不可能有一個通用的範圍,沒有在工作表上的位置,或者如果不知何故我的語法關閉。
任何幫助將不勝感激! :)
哦,夥計,這是一個偉大的答案,我唯一的問題是我通過Access VBA所以我outputing報告不能嵌入像這樣的隱藏表格。 – mandroid 2009-08-31 19:00:53