解决VBA循环中的名称冲突

时间:2016-06-03 04:28:01

标签: excel vba excel-vba

我有一个模块可以解析多张工作簿中的数据。但是,在循环过程中,我不断收到一条名称已经存在的消息,但无论我做出什么选择,它都会重复相同的消息。我尝试在消息框中输入不同的名称,但它会继续重复。有什么想法,我收到这条消息?

Sub parse()
Dim WrkBookDest As Workbook
Dim WrkBookSrs As Workbook
Dim WrkSheetDest As Worksheet
Dim WrkSheetSrs As Worksheet

Set WrkBookDest = ThisWorkbook
FolderPath = "C:\attach\"
Filepath = FolderPath & "*.xlsx"
Filename = Dir(Filepath)

With WrkSheetSrs
WrkBookDest.Sheets("Sheet1").Range("A1") = .Range("A1").Value
WrkBookDest.Sheets("Sheet1").Range("A1").NumberFormat = .Range("A1").NumberFormat
WrkBookDest.Sheets("Sheet1").Range("B1") = .Range("A2").Value
WrkBookDest.Sheets("Sheet1").Range("B1").NumberFormat = .Range("A2").NumberFormat
WrkBookDest.Sheets("Sheet1").Range("C1") = .Range("B4").Value
WrkBookDest.Sheets("Sheet1").Range("C1").NumberFormat = .Range("B4").NumberFormat
WrkBookDest.Sheets("Sheet1").Range("D1") = .Range("B5").Value
WrkBookDest.Sheets("Sheet1").Range("D1").NumberFormat = .Range("B5").NumberFormat
WrkBookDest.Sheets("Sheet1").Range("E1") = .Range("B6").Value
WrkBookDest.Sheets("Sheet1").Range("E1").NumberFormat = .Range("B6").NumberFormat
WrkBookDest.Sheets("Sheet1").Range("F1") = .Range("B7").Value
WrkBookDest.Sheets("Sheet1").Range("F1").NumberFormat = .Range("B7").NumberFormat

End With

For i = 3 To 9
WrkBookDest.Sheets("sheet1").Range("G" & (i - 3) * 56 + 1) = WrkBookSrs.Sheets(i).Range("A2:C57").Value
Next
End Sub

1 个答案:

答案 0 :(得分:2)

您要复制的其中一个单元格是已定义的名称(公式►已定义的名称►名称管理器)。通过复制和粘贴,Excel认为您正在尝试创建一个新的相同的命名范围。仅粘贴值。在单独的操作中更改Range.NumberFormat property

以下使用直接单元格值传输,然后跨越Range.NumberFormat property

'selecting cells from Title sheet and parsing them to main workbook
With WrkSheetSrs
    WrkBookDest.Sheets("Sheet1").Range("A1") = .Range("A1").Value
    WrkBookDest.Sheets("Sheet1").Range("A1").NumberFormat = .Range("A1").NumberFormat
    WrkBookDest.Sheets("Sheet1").Range("B1") = .Range("A2").Value
    WrkBookDest.Sheets("Sheet1").Range("B1").NumberFormat = .Range("A2").NumberFormat
    WrkBookDest.Sheets("Sheet1").Range("C1") = .Range("B4").Value
    WrkBookDest.Sheets("Sheet1").Range("C1").NumberFormat = .Range("B4").NumberFormat
    WrkBookDest.Sheets("Sheet1").Range("D1") = .Range("B5").Value
    WrkBookDest.Sheets("Sheet1").Range("D1").NumberFormat = .Range("B5").NumberFormat
    WrkBookDest.Sheets("Sheet1").Range("E1") = .Range("B6").Value
    WrkBookDest.Sheets("Sheet1").Range("E1").NumberFormat = .Range("B6").NumberFormat
    WrkBookDest.Sheets("Sheet1").Range("F1") = .Range("B7").Value
    WrkBookDest.Sheets("Sheet1").Range("F1").NumberFormat = .Range("B7").NumberFormat

End With

For i = 3 To 9
    WrkBookDest.Sheets("sheet1").Range("G" & (i - 3) * 56 + 1) = WrkBookSrs.Sheets(i).Range("A2:C57").Value
Next