复制并替换命名范围Excel VBA

时间:2018-05-11 16:02:05

标签: excel vba excel-vba

我正在尝试从外部工作簿复制命名范围,以替换活动工作簿中的命名范围 我得到一个类型不匹配错误,我想这可能是因为我没有将我的源称为范围。 你能帮我解决一下我的语法吗? 代码如下:

    Sub ImportLogInfo()
    Dim wkbCrntWorkBook As Workbook
    Dim wkbSourceBook As Workbook
    Dim rngSourceRange As Range
    Dim rngDestination As Range

    Set wkbCrntWorkBook = ActiveWorkbook

            Set wkbSourceBook = Workbooks.Open(Filename:="C:\Users\Documents\Proposal Log Feeder\Log Feeder A.xlsb", ReadOnly:=True)

            Set rngSourceRange = wkbSourceBook.Sheets("Log").Range("DBrange")
            wkbCrntWorkBook.Activate
            Set rngDestination = wkbCrntWorkBook.Sheets("Log").Range("DBrange")
            rngSourceRange.Copy rngDestination
            rngDestination.CurrentRegion.EntireColumn.AutoFit
            wkbSourceBook.Close False
End Sub

范围具有相同的名称,DBrange。 如果可能的话,我也只想复制A:AD中的列 如果这是不可能的,那很好。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

声明DBrange的值

dim DBrange as string
    DBrange = "A:AD"

声明工作簿

dim wkbSourceBook as workbook
    wkbSourceBook = Workbook("NameOfWorkBook")

答案 1 :(得分:1)

确保目标工作表名为日志,并且名称为 DBrange

以下代码成功复制了您所询问的范围,只要源设置和目标工作表都已正确设置即可。我可以获得类似于您遇到的错误的唯一方法是,如果我更改了目标工作表的名称,或者使用名称管理器从目标工作表中删除了命名范围 DBrange

将此代码复制/粘贴到目标工作簿的ThisWorkbook模块中,然后运行它。该代码假定 DBrange 在A列中开始。

Sub ImportLogInfo()
'copy this code into ThisWorkbook
    Dim wbCur As Workbook
    Dim wbSrc As Workbook
    Dim rngSrc As Range
    Dim rngDest As Range
    Dim strSrcFName As String

    'change this value to suit your source
    strSrcFName = "C:\Users\Documents\Proposal Log Feeder\Log Feeder A.xlsb"

    Set wbCur = Me
    Set wbSrc = Workbooks.Open(Filename:=strSrcFName, ReadOnly:=True)
    Set rngSrc = wbSrc.Sheets("Log").Range("DBrange")

    'reset the source range to subset columns A:AD of "DBrange" (30 = column AD)
    Set rngSrc = rngSrc.Range(Cells(1, 1), Cells(rngSrc.Rows.Count, 30))

    Set rngDest = wbCur.Sheets("Log").Range("DBrange")
    rngSrc.Copy rngDest
    rngDest.CurrentRegion.EntireColumn.AutoFit
    wbSrc.Close False
End Sub