2013-12-13 65 views
0

我有一個工作簿,其中一個或多個工作表代表customer。我還構建了一個customer類,以及一種將適用工作表數據加載到每個客戶對象的方法。該方法的工作原理是這樣的基於Excel中的工作表加載對象

這一切都很好......直到有人決定在同一工作簿中製作客戶工作表的副本。然後,下次打開工作簿並運行該方法時,它會找到重複的客戶密鑰,並導致崩潰和灼傷。

什麼是一個很好的解決方法,而不會阻止人們在工作簿中複製工作表?複雜程度越低越好。

+0

正確的錯誤處理? –

回答

1

除了您的客戶對象之外,還要保留對Dictionary中所有客戶對象的引用 - 以CustomerKey爲關鍵。當您創建新的客戶對象時,首先測試新的CustomerKey是否已經存在於字典中 - 在這種情況下,跳過創建新對象,而是向用戶顯示消息。

使用該詞典,您需要添加對MS Scripting Runtime的引用。那麼你的僞代碼將是這樣的:

Global gDicCustomers as Dictionary 

LoadCustomers() 
    Set gDicCustomers = New Dictionary 
    For each worksheet in the workbook 
    If the worksheet contains a named range, "CustomerKey" 
     If gDicCustomers.Exists(CustomerKey) Then 
     MsgBox "Dont screw with the customer worksheets - or at least be so decent to change the customer key, too!" 
     Else 
     Create a new customer object 
     Set its key equal to the value in the range "CustomerKey" 
     Load data from the worksheet into the object 
     gDicCustomers.Add CustomerKey, CustomerObject 
     End If 
    End If 
    Loop 
End 

這種方法的另一個優點是,你總是可以參考與gDicCustomers(CustomerKey)任何客戶對象...

相關問題