两张纸之间的单元格引用(一个具有可变名称)

时间:2017-07-31 08:48:58

标签: excel-vba vba excel

我创建了一个宏,在按钮单击时创建基于模板的新工作表,将其作为最后一个工作表放置,并在主工作表(“Lista”)(公司名称)中使用ActiveCell值命名。在新工作表中,在单元格B2:B5中,我想从主工作表中复制值(公司信息):列B到E,但行取决于所选公司。代码如下:

Sub HistoriaDostaw()

Dim wb As Workbook
Dim ws As Worksheet
Dim activeWB As Workbook
Dim FilePath As String
Dim ShtName As String
Dim CopyInfo As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Set activeWB = Application.ActiveWorkbook
FilePath = "C:\Users\DELL\AppData\Roaming\Microsoft\Szablony\HistoriaDostaw1.xltm"

On Error Resume Next

ShtName = ActiveCell.Value2

If Not WorkSheetExists(ShtName) Then

Set wb = Application.Workbooks.Open(FilePath)
wb.Worksheets(1).Copy After:=activeWB.Sheets(activeWB.Sheets.Count)

activeWB.Activate

activeWB.Sheets(activeWB.Sheets.Count).Name = ShtName

wb.Close False

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End If
End Sub

Function WorkSheetExists(ByVal strName As String) As Boolean
   On Error Resume Next
   WorkSheetExists = Not ActiveWorkbook.Worksheets(strName) Is Nothing
End Function

我尝试过使用复制/粘贴方法(放在子部分中),从单个单元格开始但不起作用:

ThisWorkbook.Sheets("Lista").ActiveCell.Offset(0, 1).Select
Selection.Copy
Sheets(activeWB.Sheets.Count).Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
    False

此方法也是:

activeWB.Sheets(activeWB.Sheets.Count).Range("B2").Value = ThisWorkbook.Sheets("Lista").ActiveCell.Range.Offset(0, 1).Value

也许我错误地引用了新创建的工作表。或者将代码行放错。你能帮我么?

1 个答案:

答案 0 :(得分:0)

我会尝试这样的事情。

ThisWorkbook.Sheets("Lista").Select
activeWB.Sheets(ShtName).Range("B2").Value = ActiveCell.Offset(0, 1).Value

如果这不是正常工作,请尝试

MsgBox activeWB.Sheets(ShtName).Range("B2").Value

MsgBox ThisWorkbook.Sheets("Lista").ActiveCell.Range.Offset(0, 1).Value

找出错误发生的位置