在打开多个Excel文件的情况下运行VBA代码(宏)-如何正确编码和声明

时间:2019-05-20 16:06:29

标签: excel vba

我创建了几个宏,但是当我打开多个Excel文件时,有时会遇到问题。由于某些原因,宏停止工作(VBA运行时错误1004)。我怀疑我必须正确地声明工作簿/工作表,但是我还不知道如何。基本了解后,我认为以下方法会起作用(在我的代码中不行,我尝试了一下,但不起作用): `

Dim wb as WorkBook
Dim ws as WorkSheet
Set wb = ActiveWorkbook
Set ws = ActiveWorkSheet
wb.ws.range("A1") = 2

`

但是,由于上述内容对我不起作用,我想我缺少一些有用的/有价值的知识。

如果有用:宏用于创建月度报告。因此,它们最初是空的,然后为一月,二月等创建工作表。

Sub ConsultantInvoicing()

    Dim CurrentMonth As String
    Dim NextMonth As String

    'Dim wb As Workbook
    'Set wb = ActiveWorkbook
    'Dim wsActiveSheet As Worksheet
    'Set wsActiveSheet = wb.ActiveSheet

    Sheets(Sheets.Count).Select

    If Range("A1") = "" Then
        Call AddFirstSheet
    Else
        Call AdditonalSheet

    End If


End Sub



Private Sub AddFirstSheet()

    CurrentMonth = Application.InputBox("Please enter what month", 
"Invoice (monthly) - What month?")
    ActiveSheet.Name = CurrentMonth
    Call NewSheetFormat


End Sub


Private Sub AdditonalSheet()

    CurrentMonth = Range("A1")

    Select Case CurrentMonth

        Case "January", "january"
            NextMonth = "February"

        Case "February", "february"
            NextMonth = "March"

        Case "March", "march"
            NextMonth = "April"

        Case "April", "april"
            NextMonth = "May"

        Case "May", "may"
            NextMonth = "June"

        Case "June", "june"
            NextMonth = "July"

        Case "July", "july"
            NextMonth = "August"

        Case "August", "august"
            NextMonth = "September"

        Case "September", "september"
            NextMonth = "October"

        Case "October", "october"
            NextMonth = "November"

        Case "November", "november"
            v = "December"

        Case "December", "december"
            NextMonth = "January"

    End Select

    Set ws = ThisWorkbook.Sheets.Add _
    (After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    ActiveSheet.Name = NextMonth
    ActiveSheet.Range("A1") = NextMonth

    Call NewSheetFormat


End Sub


Private Sub NewSheetFormat()
 'formats the sheet


    Range("A:A").ColumnWidth = 29.17
    Range("ColumnWidth").ColumnWidth = 12.5
    ..
    ..




End Sub

提前谢谢! 问候, 亚历山大

0 个答案:

没有答案