导出Excel VBA

1 篇文章 0 订阅

用Perl程序导出Excel VBA.

 

my $isAppLoaded = 0;

 

# Export Excel VBA modules
sub ExportExcelVBA
{
   my ($excelFile,$destFolder)= @_;
   my $excelApp = "";

   # Get the excel application
   GetApp(/$excelApp, 'Excel.Application');

   my $oWorkBooks = $excelApp->WorkBooks;

   my $oCurrentWorkBook = GetExistObject($oWorkBooks,$excelFile);

   if($oCurrentWorkBook eq "")
   {
      $oCurrentWorkBook = $excelApp->WorkBooks->Open($excelFile);
   }

   my $oVBProject = $oCurrentWorkBook->VBProject;

   if (not(-e $destFolder ))
   {
       `mkdir $destFolder`;
   }

   ExportVBAModules(/$oVBProject,$destFolder );
   # Close the workbook without saving
   if ($isAppLoaded == 0)
   {
       $oCurrentWorkBook->Close(0, 0, 0);
   }

   ExitApp(/$excelApp);
}

 

# Getthe exist opened object
sub GetExistObject
{
   my ($objects, $objName) = @_;
   my $count = $objects->Count;
   my $oCurrentObject ="";
   if ($count >0 )
   {
      for (my $i =1; $i<=$count; $i++)
      {
          my $oTempObject = $objects->Item($i);
          my $objectName =$oTempObject->FullName;
          if ("/L$objName" eq "/L$objectName")
          {
             $oCurrentObject = $oTempObject;
             last;
          }
      }
   }

   return $oCurrentObject;
}

 

 

# Get the Application
sub GetApp
{
   my ($app, $progID) = @_;
   eval
   {
       $$app = Win32::OLE->GetActiveObject($progID);
   };

   if ($@ or $$app eq "")
   {
       $$app= Win32::OLE->new($progID);
       $isAppLoaded = 0;
   }
   else
   {
       $isAppLoaded = 1;
   }
}

 

 

# Export the moduels of the VBA project
sub ExportVBAModules
{
   my ($oVBProject, $destFolder) = @_;
   my $oVBComponents = $$oVBProject->VBComponents;
   my $count =  $oVBComponents->Count;

   for (my $i = 1; $i <=$count; $i++)
   {
      my $module = $oVBComponents->Item($i);
      my $moduleName = $module->Name;
      my $type =  $module->Type;
      my $fileType = "";

      if ($type == vbext_ct_StdModule || $type == vbext_ct_Document )
      {
          $fileType = ".cls";
      }
      elsif ($type == vbext_ct_MSForm)
      {
          $fileType = ".frm";
      }
      elsif ($type == vbext_ct_ClassModule)
      {
          $fileType = ".bas";
      }

      if ($fileType ne "")
      {
          my $fullPath = $destFolder."//".$moduleName.$fileType;
          print "Export $fullPath/n";
          $module->Export($destFolder."//".$moduleName.$fileType);
      }

   }
}

 

# Exit the Applicatin
sub ExitApp
{
   if ($isAppLoaded == 0)
   {
      my $app = shift;
      $$app->Quit();
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值