Excel 2003(VBA) - 自定义标识符/函数/ UDF

时间:2012-12-04 16:11:24

标签: vba excel-2003

我目前正在为我的工作改写一个小型股票系统,并试图加快程序,因为它的速度很慢,我现在只做了2周的VBA。

在Excel 2003 Edition中。

我的问题(我认为)正在创建一个标识符。

我有两个,他们如下:

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


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

我的用户当前从打开的对话框中选择一个文件(WORKBOOK),我正在指定的范围内导入数据。

然而,当我来调用这些函数时,我得到“对象不支持这个属性或方法”。

我不确定这是否应该是UDF,因为我无法在任何地方看到您可以编写自己的VBA函数,而不是在VBA中编写函数以供Excel使用。

3 个答案:

答案 0 :(得分: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 :(得分: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")

答案 2 :(得分:1)

esolved it guys,谢谢你的答案:-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”中。

绕过剪贴板并更新受添加值影响的所有公式。