我目前正在为我的工作重写一个小的库存系统,并试图加快程序的速度,因为它很慢,而且我只做了 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 使用。
在您的两个示例中,"概览"和"股票"都应该是变体,而不是字符串。
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")
e解决了伙计们,感谢您的回答:-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"中。
绕过剪贴板并更新受添加值影响的任何公式。