我在工作表的单元格 C2 中编写了一个公式,在其中根据各种因素定义了一个范围。单元格 C2 中的值为 F13:G65。
我现在想使用 VBA 复制该范围,其中 VB 将单元格 C2 中的范围识别为应复制的范围。请记住,F13:G65 的范围将会改变,这就是为什么我希望 VBA 复制单元格 C2 中的任何范围。
有人可以帮我定义执行此操作的代码吗?
最佳答案
复制范围:避免“意外”
Sub CopyRange()
' Reference the workbook ('wb').
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Reference the worksheet ('ws').
Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1") ' adjust!
' Write the range address to a string variable ('rgAddress').
Dim rgAddress As String: rgAddress = CStr(ws.Range("C2").Value)
' Use 'CStr' to convert to string to avoid an error occurring
' if the cell contains an error value.
' Attempt to reference the range ('rg').
Dim rg As Range
On Error Resume Next ' defer error trapping (ignore errors)
Set rg = ws.Range(rgAddress)
On Error GoTo 0 ' disable error trapping
' Validate the range.
If rg Is Nothing Then
MsgBox "'" & rgAddress & "' is not a valid range address.", vbCritical
Exit Sub
End If
' Continue, e.g.:
rg.Copy
End Sub
关于excel - 将 VBA 范围设置为等于单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73588355/