Excel VBA:如何组合来自不同工作簿的特定工作表?

时间:2017-06-13 14:41:21

标签: vba excel-vba worksheet hssfworkbook excel

我仍然是VBA的新手,我正在尝试合并来自不同工作簿的某些工作表。

例如:

  • 我有一本名为" One"有多个工作表(A,B,C,D)。
  • 我有另一本名为" Two"有多个工作表(E,F,G,H)。

我想从工作簿一中获取工作表A,从工作簿二中获取工作表F和G.我希望将这些不同的工作表放在一个名为" Three的新工作簿中。"

工作表A和F中的字段格式完全相同,因此我还希望将这两个工作表组合在一起,并在包含A数据的单元格完成后将F数据放在A数据下的相同字段中。

任何人都可以帮我解决这个问题吗? 如果有人也为初学者提供任何VBA链接,我们将非常感激。

1 个答案:

答案 0 :(得分:2)

看看例子:

from nltk.corpus import stopwords

def remove_stopwords(word_list):
        processed_word_list = []
        for word in word_list:
            word = word.lower() # in case they arenet all lower cased
            if word not in stopwords.words("english"):
                processed_word_list.append(word)
        return processed_word_list

注意:上面的代码已写成 ad-hoc ,因此可能不完美。

<强> [EDIT2] 如果您想将数据复制到不同的表格中,请用下面的代码替换相应的代码,但首先要删除这些代码:

'enforce declaration of variables 
Option Explicit

Sub CombineWorkbooks()
Dim sWbkOne As String, sWbkTwo As String
Dim wbkOne As Workbook, wbkTwo As Workbook, wbkThree As Workbook
Dim wshSrc As Worksheet, wshDst As Worksheet

On Error GoTo Err_CombineWorkbooks

'get the path
sWbkOne = GetWbkPath("Open workbook 'One'")
sWbkTwo = GetWbkPath("Open workbook 'Two'")
'in case of "Cancel"
If sWbkOne = "" Or sWbkTwo = "" Then
    MsgBox "You have to open two workbooks to be able to continue...", vbInformation, "Information"
    GoTo Exit_CombineWorkbooks
End If

'open workbooks: 'One' and 'Two'
Set wbkOne = Workbooks.Open(sWbkOne)
Set wbkTwo = Workbooks.Open(sWbkTwo)
'create new one - destination workbook
Set wbkThree = Workbooks.Add

'define destination worksheet
Set wshDst = wbkThree.Worksheets(1)

'start copying worksheets
'A
Set wshSrc = wbkOne.Worksheets("A")
wshSrc.UsedRange.Copy wshDst.Range("A1")
'F
Set wshSrc = wbkTwo.Worksheets("F")
wshSrc.UsedRange.Copy wshDst.Range("A1").End(xlDown)
'G
Set wshSrc = wbkTwo.Worksheets("G")
wshSrc.UsedRange.Copy wshDst.Range("A1").End(xlDown)

'done!

Exit_CombineWorkbooks:
    On Error Resume Next
    Set wbkThree = Nothing
    If Not wbkTwo Is Nothing Then wbkTwo.Close SaveChanges:=False
    Set wbkTwo = Nothing
    If Not wbkOne Is Nothing Then wbkOne.Close SaveChanges:=False
    Set wbkOne = Nothing
    Set wshDst = Nothing
    Set wshSrc = Nothing
    Exit Sub

Err_CombineWorkbooks:
    MsgBox Err.Description, vbExclamation, Err.Number
    Resume Exit_CombineWorkbooks


End Sub


Function GetWbkPath(ByVal initialTitle) As String
Dim retVal As Variant

retVal = Application.GetOpenFilename("Excel files(*.xlsx),*.xlsx", 0, initialTitle, , False)
If CStr(retVal) = CStr(False) Then retVal = ""

GetWbkPath = retVal

End Function

后:

'define destination worksheet
Set wshDst = wbkThree.Worksheets(1)
祝你好运!