2012-12-04 41 views
2

我目前正在爲我的工作重寫一個小型股票系統,並試圖加快程序的速度,因爲它的速度很慢,我現在只做了2周的VBA 。Excel 2003(VBA) - 自定義標識符/函數/ UDF

在Excel 2003版中。

我的問題(我認爲)是創建一個標識符。

我有兩個,它們分別爲:

Dim QuickView As String 
    QuickView = ActiveWorkbook.Range("a1:c200").Copy 


    Dim Stock As String 
    Stock = ActiveWorkbook.Range("c1:c200").Copy 

我的用戶目前選擇的公開對話文件(練習冊),我進口規定範圍的數據。

但是,當我來調用這些函數時,我得到「對象不支持此屬性或方法」。

我不確定這是否應該是一個UDF,因爲我無法在任何地方看到你可以編寫自己的VBA函數,而不用在VBA中編寫函數來使用Excel。

+1

從代碼中不清楚你想要做什麼,所以你需要添加更多的細節。如果你想從每個範圍獲取數據,那麼你需要將變量聲明爲Variant,並使用'.Value'而不是'.Copy'。這會給你一個二維數組(即使你的第二個範圍只有一列)。 –

回答

3

在你的兩個例子中,「QuickView」和「Stock」應該是變體,而不是字符串。

Dim Stock As Variant 
Stock = ActiveWorkbook.Range("c1:c200").Copy 

請記住,您不需要將範圍指定給變量以將單元格值複製(或剪切)到其他位置。相反,你可以這樣做:

ActiveWorkbook.Sheets("Sheet1").Range("c1:c200").Copy 
ThisWorkbook.Sheets("Sheet1").range("c1") 

約定是copy_from [SPACE] put_it_here

注意:在上面的示例中,這些值將被複制到包含運行代碼的工作簿的Sheet1中。運行VBA的工作簿始終爲ThisWorkbook

+1

第二個代碼是可以的。第一個代碼不能工作AFAIK –

+0

在第一個代碼示例中,'Range(「c1:c200」)'之後的'.Copy'部分是不相關的,應該刪除。 'Workbook'沒有'Range'方法,所以'ActiveWorkbook'應該被'ActiveSheet'替代,或者更好的方法是引用一個特定的表單。我在回答中整理了一個明顯的拼寫錯誤 – barrowc

1

正如@timbur所說,你可以複製一個範圍而不必先指定它。如果要分配它,變量必須是Range(或Variant)類型,並且必須使用Set進行分配,就像任何對象分配一樣。

Dim stock as Range 'or Variant, but Range is better 
Set stock = ActiveWorkSheet.Range("c1:c200") 
'copy, and optionally paste at once 
stock.Copy Destination:=ThisWorkbook.Sheets("Sheet1").range("c1") 
+1

「Workbook」中沒有'Range'成員,因此這裏需要引用'Worksheet' – barrowc

+0

right,correct。謝謝 –

1

eSolved這傢伙,感謝您的回答:-D

Sub Button1_Click() 

Dim FileOpened As Boolean ' Holds True or False value 
Dim SourceRange As Range 
Dim TargetRange As Range 
Dim MasterWorkbook As Workbook 
Dim Row As Integer 

' Remember the current workbook we are clicking the button from. 
Set MasterWorkbook = ActiveWorkbook ' Use Set = for all complex types. 

' Identify file to open. 
ChDrive "C:" 
ChDir "c:\" 

On Error Resume Next ' Temporarily ignore errors in situation when user says no to   opening the same master file a second time. 
FileOpened = Application.Dialogs(xlDialogOpen).Show 
On Error GoTo 0 ' Reinstates normal error reporting. 

' Don't process the file if the user cancels the dialog. 
If FileOpened Then 

    ' The opened file automatically becomes the new active workbook and active worksheet. 
Set SourceRange = ActiveSheet.Range("c1:c394") 

Set TargetRange = MasterWorkbook.ActiveSheet.Range("b1:b394") 

' Copy cell values one at a time from the source range to the target range. 
For Row = 1 To 394 
    TargetRange.Cells(Row, 1).Value = SourceRange.Cells(Row, 1).Value 
Next 

ActiveWorkbook.Close 

' Set background colour of target range. 
TargetRange.Select 
With Selection.Interior 
    .ColorIndex = 6 
    .Pattern = xlSolid 
End With 


' Tell Excel to recalculate only those formulas which use the target values. 
TargetRange.Dirty 

End If 

End Sub 

對於那些有興趣在此代碼:

用戶選擇從入圍目錄中的文件,然後選擇提名範圍「C1 :c394「並將其過濾到」sheet1「中。

繞過剪貼板並更新任何受附加值影響的公式。