excel - 将 VBA 范围设置为等于单元格值

标签 excel vba

我在工作表的单元格 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/

相关文章:

vba - nextline vba 与 excel 生成电子邮件

sql - Access VBA 类型不匹配

internet-explorer - 如何使用VBA刷新IE

excel - 如何从电子表格上的按钮调用用户表单?

excel - 跨模块声明公共(public)变量

c# - 如何在 excel 中定义色标条件格式

excel - 重置Excel "Find and Replace"对话框参数

excel - 将 p 值从 reghdfe 导出到 Excel

python - 读取 .xlsx 并访问单元格值,但不按其位置

excel - 在 VBA 中使用 Excel 频率工作表函数绘制直方图