繁体   English   中英

Excel 2003(VBA)-自定义标识符/功能/ UDF

[英]Excel 2003(VBA) - Custom Identifier / Function / UDF

我目前正在为我的工作重写一个小型的库存系统,并试图加快程序的速度,因为它的速度太慢了,而且我现在才进行VBA工作了2周。

在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使用的函数。

在您的两个示例中,“ 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

正如@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")

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”中。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM