3

我目前正在为我的工作重写一个小型库存系统,并试图加速程序,因为它很慢,而且我现在只做 VBA 2 周。

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

4

3 回答 3

4

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

于 2012-12-04T20:37:02.550 回答
1

电子解决了伙计们,感谢您的回答:-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”中。

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

于 2012-12-05T10:46:43.777 回答
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")
于 2012-12-04T20:58:07.980 回答